I am a bit confused about adding classes to a collection. In this case a Dictionary.
I got liked to a "similar" thread.. but it appears to be a totally diff rent issue. My question is about putting multiple classes in a dictionary that are inherited form a common base class. The linked thread is about storing different types like int, string, double.. etc.
class ClassName
{
public string name { get; }
public ClassName()
{
name = "name";
}
}
class Unique : ClassName
{
public string uName { get; }
public Unique()
{
uName = "UniqueName?";
}
}
class YAunique : ClassName
{
public string yaName { get; }
public YAunique()
{
yaName = "YetAnotherName";
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, ClassName> doesThisWork = new Dictionary<string, ClassName>();
doesThisWork.Add("test", new Unique());
doesThisWork.Add("test2", new YAunique());
Console.WriteLine(doesThisWork["test"].name);
Console.WriteLine(doesThisWork["test"].uName); //dose not work
Console.WriteLine(doesThisWork["test2"].name);
Console.WriteLine(doesThisWork["test2"].yaName); //does not work
Unique example = new Unique();
Console.WriteLine(example.name);
Console.WriteLine(example.uName);
YAunique example2 = new YAunique();
Console.WriteLine(example2.name);
Console.WriteLine(example2.yaName);
// Pauses the console window
Pause4Input();
}
Basically in the example above I have 3 classes, 2 of which are inherited off the same class. If I initialise either of the inherited classes I can access both the base class's variable and the child class variable (the prints at the bottom of the code)....
....but what I am trying to do is place those child classes in a dictionary.
The thing is even though it "looks" kinda right... I can only access the variables in the base class using the dictionary keys.
TL;DR I am trying to work out how to have different classes added to a dictionary collection and have all the child class functions and variables and the base class functions and variables accessible.
Thanks!