In C# I want to be able to write
FooEnum f = fromValue(typeof(FooEnum), 42);
where fromValue returns MyEnum and FooEnum extends MyEnum.
I am converting some Java code to C#. The Java code has
static <T extends MyEnum> T fromValue(Class<T> c, int value) {
return (T)fromInnerValue(c, value);
}
This means that if we can write
FooEnum f = fromValue(FooEnum.class, 42);
Which will return a FooEnum without the need for an explicit casts. (This happens a lot so is worthwhile.) It is "unchecked" in the narrow sense that if fromInnerValue was to return a BarEnum instead of a FooEnum we would get a runtime cast exception instead of a compile time one.
In C#/.Net System.Type does not appear to be generic. So the function definition becomes
static T fromValue<T>(System.Type c, int value) where T : Enum {
return (T)fromInnerValue(c, value);
}
That compiles, but with Type rather than Type, so it does not really know what T is at compile time. Then a call
FooEnum f = fromValue(typeof(FooEnum), 42);
fails with "Type cannot be inferred from its arguments".
FooEnum f = fromValue<FooEnum>(typeof(FooEnum), 42);
works but has the verbosity I am trying to avoid. I think it means that fromValue has an actual run time parameter T as there is no type erasure in C#. But we have the type as that first parameter, c. But it needs to somehow be the Generic type.
Or can we go the other way in C# and make FooEnum f = fromValue(42); work?
(If it cannot be done then I would be inclined to forget about Generics and just write
FooEnum f = (FooEnum)fromInnerValue(typeof(FooEnum), 42); )
Thoughts?