简体   繁体   中英

How the default value initialized even not specified in explicit constructor in c#

Declared variable and not initialized in explicit constructor. Then how the default value initialized to the variable.is it initialization done by the implicit constructor?

Ex:

class A
{
    int i;
    public A()
    {
    }  
}

class program
{
    static void Main(string[] args)
    {
        A a = new A();
        Console.Write(a.i);
    }
}

Output: 0

If you don't initialize a member variable then it gets assigned the value default(T) where T is the type.

For reference types this is null . For bool it is false and for other value types it is whatever the state of the object would be it the memory for it was zeron-initialized. Thus for int it it 0 .

int is a value type and cannot be null unless you declare it as a nullable int (int?). It's default value is 0.

you have taken i as int , and Integer is value type with a default value is 0

Check below link, if you're new in C#

Default Value

Value Type

Reference Type

Use ? , If you don't want to assign a default value. see below example

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM