1. What are the secondary constraints?
2. What does type parameter constraint (naked type constraint mean)?
The C# allows using interfaces as type constraints; therefore for instantiation we must use specific interfaces or classes that implement this interface.
The C# allows us to specify constraints by another type constraint. When we need to enforce relationship between two type parameters we can use the naked type constraints.
Example 1:
private static List<T> ConstrainedByInterfaceMethod<T>() where T : IComparable{
return null;
}
private static List<TBase> ConvertedList<TBase, T>(IList<T> param) where T : TBase{
List<TBase> resList = new List<TBase>(param.Count);
for (int i = 0; i < param.Count; i++ )
resList.Add(param[i]);
return resList;
}
static void Main(string[] args)
{
List<string> stringList = new List<string>();
IList<object> correct = ConvertedList<object, string>(stringList);
//The type ‘string’ cannot be used as type parameter ‘T’ in the generic type or method
//’SecondaryConstraints.Program.ConvertedList<TBase,T>(System.Collections.Generic.IList<T>)’.
//There is no implicit reference conversion from ‘string’ to ‘System.Exception’.
IList<Exception> incorrect = ConvertedList<Exception, string>(stringList);
}