The follow is bad code. Please help me achieve what I’m trying to achieve, but with good code.
I want to have an object array that is derived from a base. I want to be able to use that array in BaseClass when DoStuff() runs. I know that I cannot downcast, that’s not what i’m looking to do here. I just want to be able to set Fields in the derived class, and use Fields in the base DoStuff().
public class BaseObject
{
}
public class DerivedObject : BaseObject
{
}
public class BaseClass
{
public BaseObject[] Objects;
public virtual void DoStuff()
{
// use the Objects
}
}
public class DerivedClass : BaseClass
{
public override DerivedObject[] Objects;
public override void DoStuff()
{
// Do stuff unique to the derived.
base.DoStuff();
}
}
You are looking for generics?
In the above code field of
Ttype (generic or parameter type) is declared,Tis constrained to beBaseObjector class inherited fromBaseObject, whenDerivedClassis declaredDerivedObjectis specified in place of T, so inDerivedClassObjectsfield can be used asDerivedObject[].