1

If I have classes:

class Useless
{
    private string _message ;
    public Useless(string message)
    {
        _message = message;
    }
}

class UselessFactory<T> where T : new()
{
    public Useless CreateUseless(string msg)
    {
        return new T(msg);
    }
}

Why can't I instantiate T with parameters, like I could do with the following?

return (Useless)Activator.CreateInstance(typeof(T), msg);
ProfK
  • 49,207
  • 121
  • 399
  • 775

3 Answers3

2

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor.

From the docs

Possible workaround (not the same thing)

If you make Message a public and mutable property you can do:

class UselessFactory<T> where T : UselessBase, new()
{
    public T CreateUseless(string msg)
    {
        return new T() { Message = msg };
    }
}
Johan Larsson
  • 17,112
  • 9
  • 74
  • 88
  • This would not work, Message is not a know property of variable Type `T` – Habib Apr 23 '13 at 08:02
  • Tried it, it works. Note that I added a constraint to `T : UselessBase, new()` but I agree the example is not very good and probably not what OP wants. I also made message a public property. – Johan Larsson Apr 23 '13 at 08:07
1

You could do the following:

return (T)Activator.CreateInstance(typeof(T), new object[] { msg });

I got it from this question: https://stackoverflow.com/a/731637/1522991

Community
  • 1
  • 1
  • Um, that's basically what I said I was doing in my question, but with one small correction, thanks. – ProfK Apr 23 '13 at 08:54
1

It is simply not supported at this moment.

There are work arounds:

  • Mark the type T with an interface or class (where T: MyClass) and set properties or call its methods to initialize the instance.
  • Your Activator.Activate (a slow dynamic method).
  • The fastest dynamic method is to once use reflection to find the correct ConstructorInfo and convert this into a strongly typed delegate (in your case: Func<string, T>). You can call this delegate which will construct an instance with the given parameter.
Martin Mulder
  • 12,642
  • 3
  • 25
  • 54