So for example I have two classes:
Class A
{
string property1;
string property2;
}
Class B : A
{
string property3;
string property4;
....
}
So B inherits class A’s properties. They are sitting in a list, that is sitting in a dictionary
Dictionary <string, List<A>> myDictionary = new Dictionary<string, List<A>>();
List<A> myList = new List<A>();
There is one Dictionary, containing many List’s, that all contain a mix of Class A & B objects.
While looping through, I am trying to access some properties from Class B objects, I have an if statement to find them but the program still thinks they are of type Class A and throws an error when I try and use a property3 or property4. For example:
string key = string key in dictionary;
string index = object position in list;
myDictionary[key][index].property3.someMethod();
Is there a way to tell the program that this is a class B object and allow the properties 3 & 4 to be used?
Cast the object safely as a B-type object, then check for null
Although, I would also probably say it seems like your design is off. Ordinarily, I wouldn’t expect something like this. Normally, if you’re using inheritance, you’d want a design that allows them to be used interchangeably. For example, you might implement the behavior on A as a no-op, but override it on B to actually do something. This would make it so that consuming classes need not care whether the “A” thing is really an A or a B instance.