Reputation: 11623
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();
}
}
Upvotes: 3
Views: 669
Reputation: 15242
You are defining the Property correctly, it should look like
public class BaseClass
{
public virtual BaseObject[] Objects {get; set;}
public virtual void DoStuff()
{
// use the Objects
}
}
Then you should be able to override it as
public class DerivedClass : BaseClass
{
public override BaseObject[] Objects {get; set;}
public override void DoStuff()
{
// Do stuff unique to the derived.
base.DoStuff();
}
}
It has to have the same name as the base object.
Upvotes: 0
Reputation: 16032
You are looking for generics?
public class BaseClass<T>
where T : BaseObject
{
public T[] Objects;
public virtual void DoStuff()
{
// use the Objects
}
}
public class DerivedClass : BaseClass<DerivedObject>
{
public override void DoStuff()
{
// Do stuff unique to the derived.
base.DoStuff();
}
}
In the above code field of T
type (generic or parameter type) is declared, T
is constrained to be BaseObject
or class inherited from BaseObject
, when DerivedClass
is declared DerivedObject
is specified in place of T, so in DerivedClass
Objects
field can be used as DerivedObject[]
.
Upvotes: 9