Beginner here. I am trying to find a way how to access property of object in array without always using "array[0] as ClassName" when they are not the same type of objects. No need detailed answer. You can also just recomend/guide me to where should i read about these things, because maybe the answer will be in front of me but i wont be able to recognize it because i am beginner.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vezba_9_object_ecercises
{
class Program
{
static void Main(string[] args)
{
object[] books = new object[2];
books[0] = new SomeBooks("Book_1", "Good", 22);
Console.WriteLine((books[4] as SomeBooks).name); // working
// Console.WriteLine((books[4].name); // not working, how to make it work
books[1] = new OtherBooks("Book_2", "Bad", 2);
Console.WriteLine((books[4] as OtherBooks ).name); // working
// Console.WriteLine((books[4].name); // not working, how to make it work
}
}
public class SomeBooks
{
public SomeBooks(string _name, string _likability, int _numberOfPages)
{
name = _name;
likability = _likability;
numberOfPages = _numberOfPages;
}
public string name { get; set; }
public string likability { get; set; }
public int numberOfPages { get; set; }
}
public class OtherBooks
{
public OtherBooks(string _name, string _likability, int _numberOfAuthors)
{
name = _name;
likability = _likability;
NumberOfAuthors = _numberOfAuthors;
}
public string name { get; set; }
public string likability { get; set; }
public int NumberOfAuthors { get; set; }
}
}
(books[4].name)that won't work sincebooks[4]is an object and it had nonameproperty by contract.. you will need to learn OOP more i think.. like instead of array ofobjects you could array of interfaces or abstract..asthem when you need the child class.