4

I'm trying to understand the constraints on generic type parameters in C#. What is the purpose of the where T : new() constraint? Why would you need to insist that the type argument have a public parameterless constructor?

Edit: I must be missing something. The highest rated answer says the public parameterless constructor is necessary to instantiate the generic type. If that's the case, why the does this code compile and run?

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //class Foo has no public parameterless constructor
            var test = new genericClass<Foo>(); 
        }
    }

    class genericClass<T> where T : new()
    {
        T test = new T();  //yet no problem instantiating
    }

    class Foo
    {
        //no public parameterless constructor here
    }
}

Edit: In his comment, gabe reminded me that if I don't define a constructor, the compiler provides a parameterless one by default. So, class Foo in my example actually does have a public parameterless constructor.

1
  • 7
    Don't forget that if you don't specify any constructors, you get a public parameterless constructor by default.
    – Gabe
    Mar 15, 2010 at 20:37

5 Answers 5

12

If you want to instantiate a new T.

void MyMethod<T>() where T : new()
{
  T foo = new T();
  ...
}
3
  • 1
    @Frank: You cannot inherit from a generic type parameter. Mar 15, 2010 at 19:29
  • Since my incomplete answer was getting many upvotes, I made it community wiki. Please feel free to update it to form a more complete answer.
    – Greg
    Mar 15, 2010 at 19:29
  • @Greg, how to find out on a give Type object that it has a public parameterless constructor on it? Jan 20, 2012 at 0:45
4

Also, I believe that serialization requires a public parameterless constructor...

1
  • More correctly: deserialization. I don't think serialization itself has any constructor requirements.
    – user47589
    Mar 15, 2010 at 19:48
2

I don't know about serizlization, but I can mention that COM objects require a parameterless constructor as parameterized constructors are not supported, as far as I know.

1

That is necessary whenever any method is creating an object of type T.

0

When ever you would want to write new T(); inside a generic method/class you'll need that constraint so T create<T>(/*...*/) would probably need it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.