Say I have an abstract base class BaseClass.
I’d like to give it a method that looks something like the following
public void CopyPropertiesFrom<T>(T source) where T == ThisDerivedClass : BaseClass
{
// ...
}
I want the method to be generic, but to be restricted to the most derived class of the current instance. (My method will use reflection, so I don’t actually need to override CopyPropertiesFrom in any child classes, but I would still like the compile-time type safety.)
Is there any way to express this in valid C#?
Not only is there no way of expressing this, but it would be impossible for the compiler to enforce anyway. The point of generics is that they can be checked at compile time. What would you expect this to do…
The compiler only knows about
fooasBaseClass– how should it know to complain that actually, you should be callingfoo.CopyPropertiesFrom<DerivedClass>?You can check within the method, of course – but I’m not sure I’d even make it generic: