As far as i know it is not possible to do the following in C# 2.0
public class Father { public virtual Father SomePropertyName { get { return this; } } } public class Child : Father { public override Child SomePropertyName { get { return this; } } }
I workaround the problem by creating the property in the derived class as ‘new’, but of course that is not polymorphic.
public new Child SomePropertyName
Is there any solution in 2.0? What about any features in 3.5 that address this matter?
This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code:
For the
Getmethods, covariance means thatTmust either beSor a type derived fromS. Otherwise, if you had a reference to an object of typeDstored in a variable typedB, when you calledB.Get()you wouldn’t get an object representable as anSback — breaking the type system.For the
Setmethods, contravariance means thatTmust either beSor a type thatSderives from. Otherwise, if you had a reference to an object of typeDstored in a variable typedB, when you calledB.Set(X), whereXwas of typeSbut not of typeT,D::Set(T)would get an object of a type it did not expect.In C#, there was a conscious decision to disallow changing the type when overloading properties, even when they have only one of the getter/setter pair, because it would otherwise have very inconsistent behavior (‘You mean, I can change the type on the one with a getter, but not one with both a getter and setter? Why not?!?’ — Anonymous Alternate Universe Newbie).