How to provide arguments when creating an instance of a variable T

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

The following code chunk

static T CreateControl<T>(string name)
where T : new()
{
new T(name);
}

results in Compiler Error CS0417

MSDN help tells that "If you need to call another constructor, consider
using a class type constraint or interface constraint."

Any ideas on how to achieve this?
 
If this can only be set in the ctor, then one way around this is to use
reflection; something like (not tested):

typeof(T).GetConstructor(new Type[] { typeof(string) }).Invoke(new object[]
{ name });

However: is this a UI control? Would it support being created using new()
and then having the .Name property set? This could be done as so:

static T CreateControl<T>(string name)
where T : Control, new() {
T control = new T();
control.Name = name;
return control;
}

Marc
 
Back
Top