By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,088 Members | 1,187 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,088 IT Pros & Developers. It's quick & easy.

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

P: n/a
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?
--
---------------------
Thanks
Rajiv Das
Jun 20 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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
Jun 20 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.