C # General and Types

I have a general method:

public abstract T method<T>(int arg) where T : class, new(); 

Then I implement it in a 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 members ... Why? Is there something I can add to include them or something else?

thanks

Miloud

+4
source share
2 answers

You can do this (note that I have moved some of your general options and restrictions).

 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; } } 
+3
source

C # has no specialized specialization. You simply declared a new method with the type parameter named MyType , which has nothing for the class named MyType .

You can use, or there are general restrictions that you use to declare that T is at least MyType .

Another option is to make the base type common in T (and remove the common from the method) and have a specific type : TheBaseType<MyType>

+3
source

All Articles