Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of field initialisers in .NET(apart from readability)?

I am just trying to learn about field initializers. I ran into the error - field initializers cannot use non static field, method or prop. While hunting an answer for this I came across THIS post.

Most up voted answer, to the post, suggests that 'this' doesn't exist until the constructor is called. Does anyone know why it is that way? Why couldn't 'this' have existed before field initializers are invoked?

In my mind, coming from a C/C++ background, 'this' is merely just a block of memory allocated on the heap. And it has to exist before any member of 'this' can be assigned a value. (So it definitely exists before field initializers).

like image 399
Social Developer Avatar asked Aug 11 '17 07:08

Social Developer


People also ask

What is a field initializer in C#?

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration. For more information, see Using Constructors. A field initializer cannot refer to other instance fields.

Why would you use class field in C#?

A field, in C#, is a member of a class or an object of any type that represents a memory location for storing a value. Fields are used to store data that must be accessible to multiple methods of a class and available throughout the lifetime of an object.

How are Initializers executed in C#?

Initializers execute before the base class constructor for your type executes, and they are executed in the order in which the variables are declared in your class. Using initializers is the simplest way to avoid uninitialized variables in your types, but it's not perfect.

What is object initialization?

An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.


1 Answers

When an object gets instantiated the follwing happens (simplified):

  • memory is allocated
  • field initializers are executed
  • 'this' is created, linking all the (non-static) fields to this instance

When the field initializers are executed, the individual fields are not yet linked to the instance, so you cannot refer to another field (except the static ones) because that can only work through the reference in the 'this' instance (that does not exist yet).

To avoid confusion, you could choose not to use field initializers and initialise all the fields in the constructor body but the consequence is, you always need to explicitly declare a constructor.

like image 79
Johan Donne Avatar answered Nov 10 '22 11:11

Johan Donne