Reputation: 245
I have a situation where I would like to create a dictionary that can hold parent and child types. I would like to store different child types and be able to call their data.
The problem I am running in to is that when pulling the objects out of the dictionary, they are treated as their parent type, since the dictionary type is set as the parent object. The only way I have figured out to access their additional properties is through instantiating a new object with var (see below).
Any help would greatly be appreciated. Also, if my lingo/terminology is incorrect, please feel free to correct me as I am trying to learn. Thanks!
Update: I have updated my code slightly to try to convey exactly what I am trying to do. (added the foreach loop).
public class parent
{
public string name;
}
public class child : parent
{
public int age;
}
public class library
{
}
public class Program
{
public static void Main(string[] args)
{
Dictionary<int, parent> dictionary = new Dictionary<int, parent>();
child child1 = new child();
child child2 = new child();
child1.age = 5;
child2.age = 10;
dictionary.Add(1,child1);
dictionary.Add(2,child2);
foreach(KeyValuePair<int, parent> d in dictionary)
{
Console.WriteLine(d.age);
}
}
}
Upvotes: 1
Views: 2291
Reputation: 117124
Here's another way of accessing just the child
members of the dictionary:
Dictionary<int, parent> dictionary = new Dictionary<int, parent>();
child child1 = new child();
child child2 = new child();
child1.age = 5;
child2.age = 10;
dictionary.Add(1,child1);
dictionary.Add(2,child2);
dictionary.Add(45, new parent());
foreach(var c in dictionary.Select(x => x.Value).OfType<child>())
{
Console.WriteLine(c.age);
}
That gets me just 5
& 10
and ignores the parent
object I put in the dictionary.
Upvotes: 2
Reputation: 61369
Your design is likely wrong if you are doing this, but you already have it correct.
var child1a = child1 as child;
Does not instantiate a new object. It simply downcasts to the child
type. Downcasting is a code-smell, so consider re-working your design to where this isn't necessary.
Also, as
will return null
if the cast fails, so you should be checking it:
var child1a = child1 as child;
if (child1a != null)
Console.WriteLine(child1a.age);
Finally, you never actually used the dictionary in your code, you likely wanted to do:
var child1a = dictionary[1] as child;
if (child1a != null)
Console.WriteLine(child1a.age);
To your update, that loop will never work (nor should it). Not all the objects in your collection are guaranteed to have the "age" property.
With respect to your loop, you can do this:
foreach (child item in dictionary.Values)
{
...
}
or:
foreach (KeyValuePair<int, parent> kvp in dictionary)
{
if (kvp.Value is child)
{
child item = (child)kvp.Value;
...
}
}
Which will pull out the child
items from your values collection and let you use them as such. If thats all you are doing though, a Dictionary
is way overkill here.
Upvotes: 1