iefpw
iefpw

Reputation: 7042

How to Assign Members of Generic Type in the Constructor of a Generic Type?

How do I assign a value in a generics C# class?

public class GeneralWrapper<T>
{
    public GeneralWrapper()
    {
       Datas = new ?
    }

    public T Datas { get; set; }
}

I'm writing a generic wrapper class for a List objects (any object). So I can use this class like

GeneralWrapper<List<string>> _wrapper = new GeneralWrapper<List<string>>();
_wrapper.Datas.Add("hello")

but the Datas need to be automatically initialized in the constructor like

Datas = new Datas<t>();

it seems so that I don't have to create new after I create the GeneralWrapper class.

Upvotes: 1

Views: 716

Answers (3)

JaredPar
JaredPar

Reputation: 754735

The ability to create instances of generic type parameters in C# is pretty limited. By default you really only have a few options

  • Constrain T to new() which allows new T()
  • Constrain T to class which allows null
  • Use default(T) which works for all T values

Here though it looks like you want to use complex constructors (those which take at least one parameter). There is no way to do this directly in C#. Instead you need a more indirect mechanism like a delegate / lambda or a factory pattern.

In this case though it just looks like you want to assign an initial value to Datas. Given that it's a public property the likely best approach is to do nothing and allow the consumer to use an object initializer to set the property themselves. For example.

var x = new GeneralWrapper<MyType>() {
  Datas = new MyType("hello", "world");
};

Or if you want the value to always be assigned then force them to pass the value to the constructor

public GeneralWrapper(T datas) {
  Datas = datas;
}

Upvotes: 2

Travis
Travis

Reputation: 10547

public class GeneralWrapper<T> where T : class, new()
{
    public GeneralWrapper()
    {
       Datas = new T();
    }

    public T Datas { get; set; }
}

http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx Has the answer.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could use a constraint on your generic type:

public class GeneralWrapper<T> where T: new()
{
    public GeneralWrapper()
    {
       Datas = new T();
    }

    public T Datas { get; set; }
}

The new() constraint indicates that T must be a type that posses a default, parameterless constructor. This is verified at compile-time and allows you to instantiate this object from within the generic class.

Upvotes: 6

Related Questions