Tips and Tricks in a world of Mix

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()
{…}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: