For structs, should I call the constructor explicitly in C #?

Question about the structures. When I declare a variable / object of type struct (I don’t know which one is better) or an array or list of structures, do I need to call the constructor explicitly as objects, or just declaring it as sufficient as variables?

+4
source share
2 answers

Structures in C # can be created with or without a constructor call. In the case when the constructor is not called, the struct members will be initialized with default values ​​(essentially nullified), and the struct cannot be used until all its fields have been initialized.

From the documentation:

When creating a structure object using the new operator, it is created and the corresponding constructor is called. Unlike classes, structures can be instantiated without using a new operator. If you do not use the new one, the fields will remain unassigned, and the object cannot be used until all fields are initialized.

The following are some examples:

 struct Bar { public int Val; public Bar( int v ) { Val = v; } } public void Foo() { Bar z; // this is legal... z.Val = 5; Bar q = new Bar(5); // so is this... q.Val = 10; // using object initialization syntax... Bar w = new Bar { Val = 42; } } 

Arrays of structures differ from one structural variable. When you declare an array of type struct, you declare a reference variable - as such, you must select it using the new operator:

 Bar[] myBars = new Bar[10]; // member structs are initialized to defaults 

You can also use array initialization syntax if your structure has a constructor:

 Bar[] moreBars = new Bar[] { new Bar(1), new Bar(2) }; 

You can become more complicated than that. If your struct has an implicit conversion operator from a primitive type, you can initialize it as follows:

 struct Bar { public int Val; public Bar( int v ) { Val = v; } public static implicit operator Bar( int v ) { return new Bar( v ); } } // array of structs initialized using user-defined implicit converions... Bar[] evenMoreBars = new Bar[] { 1, 2, 3, 4, 5 }; 
+13
source

Struct is a Value Type in C #, so it uses stack memory, not a bunch.

You can declare a structural variable in the usual way, for example int a = 90; ,

int is a type of structure in C #.

If you use the new operator, then the corresponding constructor will be called.

0
source

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


All Articles