Link to home
Start Free TrialLog in
Avatar of Unimatrix_001
Unimatrix_001Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Default parameter for a generic class.

Hello,

Is there a way I can give TType a default value, for example:

public interface MyInterface<TType=MyDefinedType>{
	....
}

Open in new window


Thanks,
Uni
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

I'm not sure if this can help 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
Avatar of Unimatrix_001

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
ASKER CERTIFIED SOLUTION
Avatar of Asim Nazir
Asim Nazir
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you. :)