Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a property with the same name but of different type [duplicate]

Tags:

c#

inheritance

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.

like image 237
John Tan Avatar asked Dec 13 '25 08:12

John Tan


1 Answers

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.

like image 92
Zohar Peled Avatar answered Dec 15 '25 09:12

Zohar Peled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!