2

I am wondering if there is a way to override a variable with the same name with a different type in the derived class. Something along the lines of this (although this code will not compile):

public class A
{
    public virtual Point2D Point; // Represent a 2D point
}

public class B : A
{
    public override Point3D Point; // Represent a 3D point
}

The reason for doing this is that A and B may share similar properties, just that the dimension of the Point is different.

John Tan
  • 1,331
  • 1
  • 19
  • 35
  • 1
    Just for reference: [What is Shadowing ...](http://stackoverflow.com/questions/673779/what-is-shadowing) – MrPaulch May 11 '16 at 07:05

2 Answers2

6

You can't override it but you can use the new keyword to stimulate override (shadowing).

Note: if the reference to class B is of type A, you will get the A property and not the B property.
This means that you must be very careful when using the new keyword for shadowing base class properties.

Here is a StackOverflow post about the differences between new and override

Using the new keyword instead of overriding properties can be very useful when the derived class property type is derived from the base class property type.

Community
  • 1
  • 1
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • 1
    In general, shadowing members from base classes leads to a whole class of new problems, I would advice against doing this. – Lasse V. Karlsen May 11 '16 at 07:10
  • @LasseV.Karlsen I agree It should be used with extra caution, but can be very useful when used properly. I've added a clarification in my answer. – Zohar Peled May 11 '16 at 07:11
5

You are talking about Generics.

public class YourBaseClass<T>
    where T: class
{
    public T Point { get; set; }
}

public class A : YourBaseClass<Point2D>
{
}

public class B : YourBaseClass<Point3D>
{
}

So, when you are calling

var a = (new A()).Point;
var type = a.GetType();

the type of the point of the A instance is Point2D (or null in this example, since the reference typed property is not initialized yet.)

var point2D = (new A()).Point as Point2D;

Note: the reason to use generics in this situation is to specify the return type of the Point property for the derived classes.
Using generics is much better solution than to use the virtual keyword in order to hide the base class's property and define a new one (aka perform shadowing). Now you have a base property which has a "settable" return type, instead of having multiple properties which hide each other.

aniski
  • 1,263
  • 1
  • 16
  • 31