Here is an example of the code that I’m working with:
BaseClass class1;
if (userControl.Key == 100)
{
class1 = new DerivedClass1();
//This does not work, but it seems like it should
class1.PropertyInDerivedClass1 = 7
//This does work, but why should I have to cast something that I just instantiated?
((DerivedClass1)class1).PropertyInDerivedClass1 = 7;
}
else
class1 = new DerivedClass2();
Is there anything that I can do to be able to more easily access properties and methods within derived classes?
If you wish to use variables of the derived class, you need to address them using a reference with that specific type.
To summarize, the bug in your example code was to access the properties using a reference with the base class type instead of derived class.