kpozin
kpozin

Reputation: 26969

Restrict instance method's parameter to instance's type

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#?

Upvotes: 0

Views: 78

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503090

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...

BaseClass foo = new DerivedClass();
foo.CopyPropertiesFrom<BaseClass>(new OtherDerivedClass());

The compiler only knows about foo as BaseClass - how should it know to complain that actually, you should be calling foo.CopyPropertiesFrom<DerivedClass>?

You can check within the method, of course - but I'm not sure I'd even make it generic:

public void CopyPropertiesFrom(BaseClass other)
{
    if (other.GetClass() != GetClass())
    {
        throw new ArgumentException("...");
    }
}

Upvotes: 1

Femaref
Femaref

Reputation: 61497

No, there isn't. You can only allow a class and any derived (irrelevant the depth of inheritance).

Upvotes: 1

Related Questions