Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it important to have a public parameterless constructor in C#?

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.

like image 258
raven Avatar asked Dec 01 '22 06:12

raven


1 Answers

If you want to instantiate a new T.

void MyMethod<T>() where T : new()
{
  T foo = new T();
  ...
}
like image 68
3 revs, 3 users 45% Avatar answered Dec 04 '22 21:12

3 revs, 3 users 45%