When is it important to have an open constructor without parameters in C #?

I am trying to understand the limitations for type type parameters in C #. What is the purpose of the where T : new() constraint? Why do you need to insist that the type argument has an open constructor with no parameters?

Edit: I have to miss something. The highest rating says that to create a typical type, an open parallel-free constructor is needed. If so, why is this code compiled 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 did not define a constructor, the compiler would provide a parameter without parameters by default. So, the Foo class in my example actually has an open constructor with no parameters.

+4
source share
5 answers

If you want to instantiate a new T

 void MyMethod<T>() where T : new() { T foo = new T(); ... } 
+12
source

In addition, I believe that serialization requires a public constructor without parameters ...

+4
source

I do not know about serizlization, but I can mention that COM objects require a constructor without parameters, since parameterized constructors are not supported, as far as I know.

+2
source

This is necessary when any method creates an object of type T

+1
source

When you want to write new T(); inside a generic method / class, you will need this restriction, so T create<T>(/*...*/) may need

0
source

Source: https://habr.com/ru/post/1304193/


All Articles