Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does the constructor of a class or struct initialize the fields to their default values or not?

class aa{

    public int j=8;
    int f;

    public aa() {
        f=99;
    }

}

struct  bb {

    public int v = 7;
    int l;

    public bb() {
        l = 88;
    }

}

I am kind of confused as I am learning about the structs.

let’s say if I create an instance of class aa, is the field j initialized to 8 which is NOT done by the constructor ? and field f is first defaulted to 0, again NOT by the constructor and then initialized to 99 in a constructor

And let’s say if I create an instance of struct bb, is the v initialized to 7 which is NOT done by the constructor? And field l is FIRST defaulted to 0 NOT but the constructor? And then initialized to 88 by the constructor

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The Structure types (C# reference) documentation page describes how structs are initialized. Note that the behavior has changed a bit in recent versions of the language. In C# 11, the compiler ensures that any fields that you do not initialize, either in the constructor or in the field declaration, are assigned their default values.

Also, the Fields (C# Programming Guide) documentation page describes how fields in general are initialized:

A field can be given an initial value by using the assignment operator when the field is declared.

And also:

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.

If your concern is a performance one around fields being initialized twice i.e. once with their initial value assigned as part of their declaration and once in the constructor, then I’d expect the compiler to be smart enough to optimize away any redundant assignments

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading