-1

I want to make a method which use generic. This method is implemented from an abstract class. In this method, i cannot use field of the generic type.

So, I have :

public abstract class AbstractClass {
    public abstract T Get<T>(T begin) where T: AbstractClass;
}

And the class which implement it:

public class MyClass: AbstractClass {
    public int id;
    public override MyClass Get<MyClass>(MyClass begin) {
        begin.id = 0; // cannot access to "id"
        return begin;
    }
}

The issue appear in "Get" method implementation. I cannot use MyClass's field or method because it consider it as an AbstractClass object and not MyClass one.

I tried to manually set Get<mypackege.MyClass> to force it to use the class and access to his content, but i failed.

  • unless you have C#9 with co-variant return-types you cannot even override the base-method with a more derived type. You need `public override T Get(T begin) where T: AbstractClass;` in your derived class. – MakePeaceGreatAgain Feb 10 '21 at 15:21
  • 1
    @HimBromBeere They're ()trying to) change the parameters, so even covariant return types wouldn't help. – Servy Feb 10 '21 at 15:23
  • Imagine this was possible. How would you expect clients to know what type to provide here: `AbstractClass a = GetMyClass(); a.Get(huuum, what here??)`. A client has no clue about the fact that you want a `MyClass`, so he can also provide `AnotherClass`. That is what abstraction is about: don´t rely on **specifcs**, but on common stuff. – MakePeaceGreatAgain Feb 10 '21 at 15:32

1 Answers1

1
public abstract class AbstractClass<T> where T : AbstractClass<T>
{
    public abstract T Get(T begin);
}

public class MyClass : AbstractClass<MyClass>
{
    public int id;

    public override MyClass Get(MyClass begin)
    {
        begin.id = 0; // cannot access to "id"
        return begin;
    }
}
Timothy Stepanski
  • 1,186
  • 7
  • 21
  • This is called [Curiously Recurring Template Pattern](https://ericlippert.com/2011/02/02/curiouser-and-curiouser/) – Charlieface Feb 10 '21 at 15:57