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
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:
Then, an extension that adds support for children:
Though, that’s only a partial solution, as you don’t get a way to handle grandchildren.