tags:

views:

44

answers:

1

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

+5  A: 

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

Cat cat = reader.Read<Cat>();
Marc Gravell
Nice, thanks, that should do the trick nicely...
ng