Tips and Tricks in a world of Mix

Posts tagged ‘init generic’

Instantiate a new generic object inside a generic class

Suppose you want to instantiate a new generic object inside a generic class. The problem is the C# compiler does not know whether the type argument the client will use has a matching constructor, and it will refuse to compile the instantiation line.

To address this problem, C# allows you to constrain a generic type parameter such that it must support a public default constructor. This is done using the new() constraint. For example, here is a different way of implementing the default constructor of the generic Node from Code block 3.

class Node where T : new()
{
public K Key;
public T Item;
public Node NextNode;
public Node()
{
Key = default(K);
Item = new T();
NextNode = null;
}
}
You can combine the constructor constraint with derivation constraint, provided the constructor constraint appears last in the constraint list:

public class LinkedList where K : IComparable,new()
{…}

Tag Cloud

%d bloggers like this: