karthi
karthi

Reputation: 470

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

Upvotes: 1

Views: 1420

Answers (3)

Pankaj Rawat
Pankaj Rawat

Reputation: 4573

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

enter image description here

Upvotes: 0

mp7
mp7

Reputation: 151

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

Upvotes: 0

Sean
Sean

Reputation: 62472

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.

Upvotes: 4

Related Questions