Unimatrix_001
asked on
Default parameter for a generic class.
Hello,
Is there a way I can give TType a default value, for example:
Thanks,
Uni
Is there a way I can give TType a default value, for example:
public interface MyInterface<TType=MyDefinedType>{
....
}
Thanks,
Uni
ASKER
Hi Dhaest,
Thanks for the comment - unfortunately I don't think that's quite what I'm after. I'm simply wanting to make it so when I use an interface I don't have to specify TType and let it default to something.
Thanks,
Uni
Thanks for the comment - unfortunately I don't think that's quite what I'm after. I'm simply wanting to make it so when I use an interface I don't have to specify TType and let it default to something.
Thanks,
Uni
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you. :)
Constructor Constraint
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 <K,T> from Code block 3.
class Node<K,T> where T : new()
{
public K Key;
public T Item;
public Node<K,T> 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<K,T> where K : IComparable<K>,new()
{...}
Source: An Introduction to C# Generics
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
default Keyword in Generic Code (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx