Type inference from generic methods

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);
}

      

This way I can do the following: parameter constraint and return type inference.

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

      

I was hoping that something like this would work in C #, but I'm not sure if it would.

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

      

And and do it.

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

      

Is something like this possible in C #?

+2


a source to share


1 answer


Yes, but you want typeof(T)

, not T.GetType()

and:



Cat cat = reader.Read<Cat>();

      

+5


a source