ng.
ng.

Reputation: 7189

Inferring type from method generics

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#?

Upvotes: 2

Views: 181

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

Yes, but you want typeof(T), not T.GetType(), and:

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

Upvotes: 5

Related Questions