kord
kord

Reputation: 121

Interface describing method which uses some parameter of this class

I have a couple of classes which realize one method:

class ClassA : BaseClass
{
    void Copy(ClassA a) {}
}

class ClassB : BaseClass
{
    void Copy(ClassB b) {}
}

I want to describe these methods in the interface. Is it possible?

Upvotes: 0

Views: 54

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176896

you can make use of Generic interface , for example as below

interface ICopy<T>
{
  void Copy<T>(T t)
}

Class A: ICopy<A>,BaseClass//(if you need baseclass)
{
  public void Copy(A a)
  {}
}
Class B: ICopy<B>,BaseClass//(if you need baseclass)
{
  public void Copy(B b)
  {}
}

you can also try ICloneable inbuilt interface , if you just want to make clone of you class,

This is just suggestion

class Rock : ICloneable
{
    int _weight;
    bool _round;
    bool _mossy;

    public Rock(int weight, bool round, bool mossy)
    {
        this._weight = weight;
        this._round = round;
        this._mossy = mossy;
    }

    public object Clone()
    {
        return new Rock(this._weight, this._round, this._mossy);
    }    
}

Upvotes: 1

adjan
adjan

Reputation: 13652

Use a generic interface. Using where you can constrain the type parameter T to BaseClass and its derived types.

interface Interface<T> where T : BaseClass 
{
    void Copy<T>(T t);
}

class ClassA : BaseClass, Interface<ClassA>
{
    public void Copy(ClassA b) {}
}

class ClassB : BaseClass, Interface<ClassB>
{
    public void Copy(ClassB b) {}
}

Upvotes: 1

Related Questions