C# generics syntax is much better than the nearest contender C++. Consider the following generic declaration in C++
template <typename T> // can use <class T> as wellclass GenClass{};
template
class
{
};
I always felt the need to use the typename keyword is without any purpose. Most developers kept using <class T>. The designers of C# showed that the usage of template is also not required. The short and sweet syntax in C# is
class MyClass<T>{ }
}
Constraint syntax sucks
This does not mean that everything is as small and sweet in C#. The usage of the struct keyword to indicate value type constraint is one such example. Say for a generic type I want to put a restriction that the type parameter can only be a value-type. I have to do it as follows
class MyClass<T> where T: struct{ }MyClass<int> mc = new MyClass<int>();
MyClass
This is very un-intuitive because even for integral types like Int I need to use struct as the constraint.
Similar issue is with specifying constraints on multiple type parameters. Consider the following
class MyClass<T,U> where T: struct where U: class{ }
Only if I break the constraint to two lines can you read it
class MyClass<T,U> where T: struct where U: class{}
There should have been some delimiter in between consecutive where to make the whole thing more readable.
The rules regarding the order of constraints initially taxes your memory but you get used to it soon. If I need a constraint that the type has to be a reference type that must have a public parameterless constructor I need to do the following
class MyClass<T> where T: class, new(){}
Here the order is important as class has to be the first contraint and new() has to be the last.