views:

54

answers:

2

Hi,

Say I have an object,

Class A<T, T2>
{
   public T MyObject {get;set;}
   public IList<A<T2>> MyChildren {get;set;} 
}

Problem is, sometimes I dont have children, so I dont want to declare the children type aka T2, any idea? I cannot pass in like

A a = new A<string, Nullable>(); as it is throwing an error.

Thanks

+2  A: 

There's no way to specify a "null" for a Generic Type parameter - if you declare them on the class, they're mandatory when you use that class.

If you think about it, this makes sense, because without T2, your class will be partially undefined, which isn't something that machines can handle well.

What you probably need to do is to split your class into two. First, your class with no children:

class Widget<T>
{
    public T MyObject { get; set; }
}

Then, an extension that adds support for children:

class WidgetWithChildren<T,T2>: Widget<T>
{
    public IList<Widget<T>> MyChildren { get; set; }
}

Though, that's only a partial solution, as you don't get a way to handle grandchildren.

Bevan
A: 

Nullable is a genric it self so you have to do something like

new A<string, Nullable<?>>(); 

You use Nullable to make Value types (e.g. int) able to be null but if you use a Referense Type (e.g. class) it can be null anyway. My tip is to use a base class for A, if you don't have one use Object.

new A<string, Object>(); 
zwi