C# generics: Constraints on Type Parameters
Posted by jpluimers on 2011/03/10
I usually forget the exact details on C# constraints when using generics.
One of the especially irritating things is that you cannot apply all the constraints you want.
Some built-in language features are covered by special types in the .NET framework class library, for instance enums.
Which means that code like this will not compile:
// Error 1 Constraint cannot be special class 'System.Enum'
public static T StringToEnum(string name) where T : System.Enum
{
return (T)Enum.Parse(typeof(T), name);
}
You need to replace it with the code below, which uses the fact that an enum is a ValueType (hence the struct constraint) implementing the interfaces IComparable, IFormattable and IConvertible constraints:
public static T StringToEnum(string name) where T : struct, IComparable, IFormattable, IConvertible
{
return (T)Enum.Parse(typeof(T), name);
}
You use it like this:
string configValue = "Absolute";
System.UrlKind result = StringToEnum<System.UrlKind>(configValue);
So now you have some code to convert a string to an enum in an almost fully typesafe way :-)
–jeroen






Leave a comment