Lance
Lance

Reputation: 261

C# base class/Interface with a generic method that accepts the derived class as a parameter

I would like to have a method defined on the base class (and in an interface) that accepts a derived class as its parameter.

i.e.

abstract class Base : IBase
{
    public void CloneMeToProvidedEntity(??? destination) {};
}

public class Derived : Base
{
     public override void CloneMeToProvidedEntity(Derived destination)
     {
         blah blah ....
     }
}  

I would be eternally grateful if someone can tell me what the Interface would look like and how to do this... or if possible

With Anticipation

Lance

Upvotes: 0

Views: 3807

Answers (2)

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

You're probably looking for:

interface IBase<T>
{
    void CloneMeToProvidedEntity(T destination);
}

public abstract class Base<T> : IBase<T>
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {

    }
}

Thanks @Phil

Upvotes: 5

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

You can use a generic class where the generic type have to be of type IBase :

public abstract class Base<T> : IBase where T : IBase
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {
        // blah blah ....
    }
}

Upvotes: 1

Related Questions