Example 1
Assume a method that decides which method should be used to convert a value.
public static TTarget ConvertValue<TTarget>(object value)
{
Type t = typeof(TTarget);
if (t.IsEnum)
return ParseEnum<TTarget>(value);
else //if ...
return ...;
}
Some methods that handle the value have a generic type parameter with constraints.
public static TEnum ParseEnum<TEnum>(object value)
where TEnum : struct
{
//do something
return ...;
}
The compiler doesn't allow this approach because the type TTarget
isn't necessarily a struct
and can become NULL
and thus cannot be used as TEnum
.
Example 2
Assume having a generic method without constraints and a method with additional constraints:
public void DoStuff<T>(T obj)
{
if (obj is IComparable && obj is ICloneable)
DoSpecialStuff<T>(obj);
}
public void DoSpecialStuff<T>(T obj)
where T : IComparable, ICloneable
{
}
This also doesn't work because there is (afaik) no way to cast to multiple interfaces.
Is it possible to reuse a generic type to call a method with additional constraints?