Reputation: 5390
I have a generic method something like:
public abstract T method<T>(int arg) where T : class, new();
Then I implement it in the child class
public MyType method<MyType>(int arg){
MyType e = new MyType();
e.doStuff (arg); // ERROR HERE
return s;
}
But I can't access MyType's members... How come ? Is there something I can add to enable them or something ?
Thank you
Miloud
Upvotes: 4
Views: 432
Reputation: 47038
You can do like this (note that I have moved some of your generic parameters and constraints around).
public class MyType
{
public void doStuff(int i){}
}
public abstract class ABase<T>where T : class, new()
{
public abstract T method(int arg);
}
public class AChild : ABase<MyType>
{
override public MyType method(int arg)
{
MyType e = new MyType();
e.doStuff(arg); // no more error here
return e;
}
}
Upvotes: 3
Reputation: 1062502
C# does not have template specialization. You nave simply declared a new method with the type-parameter named MyType
, which has nothing to do with the class named MyType
.
You can cast, or there are generic constraints you use to declare that T
is at least a MyType
.
Another option would be to make the base-type itself generic in T
(and remove the generic from the method), and have the concrete type : TheBaseType<MyType>
Upvotes: 3