Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?

Tags:

stack

c#

clr

struct

I would like to try this code:

public struct Direction
{
   private int _azimuth;

   public int Azimuth
   {
     get { return _azimuth; }
     set { _azimuth = value; }
   }       

   public Direction(int azimuth)
   { 
      Azimuth = azimuth
   } 
}

But it fails on compilation, I understand that struct need to init all its fields. but i am trying to understand what happens under the CLR\IL hoods. why it need all the fields before any other method\property\this etc.

Thanks.

like image 358
rabashani Avatar asked Apr 06 '09 12:04

rabashani


People also ask

Do fields have to be initialized?

For more information, see Constants. A field can be declared required. A required field must be initialized by the constructor, or by an object initializers when an object is created.

Do you have to initialize all variables in constructor?

in short.. it's fine to not initialize your member variables in the constructor as long as you initialize them somewhere in the class before using them.. Save this answer.

Why initialization list?

Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

What is field initialization?

A field initializer allows you to initialize a field inline, instead of inside of a constructor. For example, instead of doing: class MyClass() { int a; int b; public MyClass() { a = 5; b = 3; } }


1 Answers

Value Types are created on the stack (unless nested within a reference type) There is something about fields/locations on the stack that the CLR can't guarantee that they will be zeroed out (contrary to fields/locations on the managed heap which are guaranteed to be zeroed out). Hence they must be written to before being read. Otherwise it's a security hole.

The struct's default ctor (which takes no parameters and which you're not allowed to explicitly specify) zeroes out all fields of a struct and hence you can use a struct after you do.

new BimonthlyPairStruct()

However when you implement your parameterized ctor, you must ensure that all fields have been initialized - which is required for the CLR to pass your code as safe/verified .

See Also: CLR via C# 2nd Ed - Pg 188

like image 152
Gishu Avatar answered Oct 14 '22 08:10

Gishu