Reputation: 3697
Say I have a couple classes;
public class A {
public int value;
public A(int value) {
this.value = value;
}
}
public class B : A {
public B(int value) : base(value) { }
}
public class Base {
public A someobject;
public Base(A someobject)
{
this.someobject = someobject;
}
}
If I wanted to derive from class Base
, I could write this;
public class Derived : Base {
public Derived(A someobject) : base(someobject) { }
}
But is it possible to change the datatype of the someobject
field to be a derived subclass, like in this example?
public class Derived : Base {
public B someobject;
public Derived(B someobject) : base(someobject) { }
}
Upvotes: 3
Views: 60
Reputation: 27367
No, it's not possible - it would be dangerous to do so. Just a note: you're currently using fields, not properties, which do not allow you to override them at all (though you can hide the base field). However, even with properties, you still cannot change the return type of the property when overriding.
Consider the following:
void Main()
{
Base myThing = new Derived();
//We view it as a Base object, so we can assign any Animal to MyAnimal
myThing.MyAnimal = new Cat();
//Now let's cast it back to Derived
Derived myCastThing = (Derived)myThing;
myCastThing.MyAnimal; //We expect a Dog, but we get a Cat?
}
public class Base
{
public virtual Animal MyAnimal { get; set; }
}
public class Derived : Base
{
public override Dog MyAnimal { get; set; }
}
public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }
You can achieve what you want using generics, however:
public class Base<TAnimalType> where TAnimalType : Animal
{
public virtual TAnimalType MyAnimal { get; set; }
}
public class Derived : Base<Dog>
{
public override Dog MyAnimal { get; set; }
}
Upvotes: 5