If I have a generic method that is constrained to be type ‘int’ then surely I should be able to cast an integer to the generic T type. For example…
public T ExampleMethod<T>(int unchanged) where T : int
{
return (T)unchanged;
}
…the compiler complains that Cannot convert type ‘int’ to ‘T’ but I have a constraint indicating that the target is as integer. So surely it should work?
Update:
The actual scenario is that I want to a helper method that returns an enum value. So my ideal helper method would be more like this….
public T GetAttributeAsEnum<T>(XmlReader reader, string name) where T : enum
{
string s = reader.GetAttribute(name);
int i = int.Parse(s);
return (T)i;
}
…and use it like this…
StateEnum x = GetAttributeAsEnum<StateEnum>(xmlReader, "State");
CategoryEnum y = GetAttributeAsEnum<CategoryEnum>(xmlReader, "Category");
OtherEnum z = GetAttributeAsEnum<OtherEnum>(xmlReader, "Other");
…but you cannot constrain by enum.
“Only class or interface could be specified as constraint.” (c) ReSharper
int (Int32) is just a struct. You can constrain that T is a struct. but you can’t use any struct as constraint.
the whole list of possible constraints you can find here – http://msdn.microsoft.com/en-us/library/d5x73970.aspx
UPD
and for Enum constraint see this question – Is there a workaround for generic type constraint of "special class" Enum in C# 3.0?