Yevgeni Grinberg
Yevgeni Grinberg

Reputation: 357

Overriding abstract method with generics

I have an abstract base class that is defined like this:

public abstract class MyBaseClass<T>

The class contains a definition for the method Get:

protected abstract MyBaseClass<T> Get(T id);

I create MyClass using MyBaseClass:

public class MyClass : MyBaseClass<string>

Now I have to implement Get, but don't know how to define it:

public override MyClass Get(object id)

or

public override MyClass Get(string id)

In both cases I will have to mention string as T and I would like to avoid it.

What is the correct way to override Get ?

Thank You.

Upvotes: 0

Views: 227

Answers (3)

Tafari
Tafari

Reputation: 3059

Implement abstaract class as follows:

public abstract class  MyBaseClass<T>
{
    protected abstract MyBaseClass<T> Get(T id);

    protected abstract MyBaseClass<T> Get(string id);
}

And the extending class:

class Class1 : MyBaseClass<Object>
{
    protected override MyBaseClass<object> Get(object id)
    {
        return (MyBaseClass<object>) id;
    }

    protected override MyBaseClass<object> Get(string id)
    {
        return FindMyBaseClass(id)
    }
}

Upvotes: 0

Servy
Servy

Reputation: 203802

When you stated the interface you were implementing you specified the generic argument as string when you wrote (: MyBaseClass<string>), as such the only way for you to implement the Get method is to use string in place of all values for T. If you want users of your class to be able to use other types then you need to make the implementing class generic as well:

public class MyClass<T> : MyBaseClass<T>
{
    protected override MyBaseClass<T> Get(T id)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 2

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

public abstract class MyBaseClass<T>
{
    protected abstract MyBaseClass<T> Get(T id);
}

public class MyClass : MyBaseClass<string>
{
    protected override MyBaseClass<string> Get(string id)
    {
        return FindById(id);//implement your logic
    }
}

Upvotes: 1

Related Questions