Inferring type from method generics

Posted by ng on Stack Overflow See other posts from Stack Overflow or by ng
Published on 2010-04-26T22:25:07Z Indexed on 2010/04/26 22:33 UTC
Read the original article Hit count: 174

Filed under:
|
|

I am from a Java background and I am looking from the equivalent in c# for the following.

public interface Reader {
   <T> T read(Class<? extends T> type);
}

Such that I can do the following, constraining the parameter and inferring the return type.

Cat cat = reader.read(Cat.class);
Dog dog = reader.read(Dog.class);

I was hoping something like this would work in c# but I am not sure it will.

public interface Reader {
   T Read<T>();
}

And and do this.

public class TypeReader : Reader {
   public T Read<T>() {
      Type type = T.GetType();
      ...
   }
}

Is something like this even possible in c#?

© Stack Overflow or respective owner

Related posts about c#

Related posts about java