Alex
Alex

Reputation: 3968

Create instance of class with member of Type T, without specifying T type

I have a class of this structure:

public class ClassName<T>
{
    public int Id {get;set;}
    public List<T> ObjectList { get; set; }
}

A collection of ClassName is situated in ParentClass

public ParentClass
{
    public List<ClassName<T>> Property {Get;set;}
    //Other properties...
}

To create an instance of this class, I would do the following:

var item = new ClassName<string>();

Is it possible to create an instance of this class without specifying the type of T ?

I have tried

var item = new ClassName<null>();
var item = new ClassName();

But obviously these do not work....

Upvotes: 1

Views: 144

Answers (2)

Mong Zhu
Mong Zhu

Reputation: 23732

Is it possible to create an instance of this class without specifying the type of T ?

In short: NO.

concerning your comment as why you want to do that:

Because not all instances of the class require this variable

the I would suggest to subdivide the classes.

public class ClassNameBase
{
    public int Id {get;set;}
}

public class ClassName<T> : ClassNameBase
{
    public List<T> ObjectList { get; set; }
}

This way you create object that need the list with a specific type. Due to inheritance they will have all other properties also that the base class provides.

EDIT:

If you want to mix the different cases of objects with and without the ObjectList you can create a collection of the base type:

public ParentClass
{
    public List<ClassNameBase> Property {Get;set;}
    //Other properties...
}

now all the different brothers will fit nicely into the same list Property.

If you want to access the ObjectList in one of the elements you need to cast them:

ClassName<int> temp = Property[0] as ClassName<int>;

if(temp != null)
{
    temp.ObjectList.Where(....
}

Upvotes: 5

Antoine V
Antoine V

Reputation: 7204

You can't do that because if you don't precise the type T, how .NET know to init the type of the objects in your list.

But FYI, you can do a simple inherit, for example:

public static void Main(string[] args)
{
    var c = new MyClass();
    var d = new MyClass<long>();
}

class MyClass<T>
{
    public List<T> ObjectList { get; set; }
}

class MyClass: MyClass<int>
{
}

With this code above, when you write new MyClass();, it inits your list with type int by default.

Upvotes: 0

Related Questions