Reputation: 7042
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
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
T
to new()
which allows new T()
T
to class
which allows null
default(T)
which works for all T
valuesHere 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
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
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