Reputation: 1303
See my code below
My question is: I am not initializing the default value of eId
and eName
, but still the attributes get initialized to default values.
Is CLR doing this?
class Employee
{
int _empId;
String _eName;
public Employee()
{
// I am not initializing the attributes here
}
public void Disp()
{
Console.WriteLine("Id:: {0} Name:: {1}", _empId, _eName);
}
}
class Program
{
static void Main(string[] args)
{
new Employee().Disp();
}
}
Upvotes: 1
Views: 583
Reputation: 660138
I am not initializing the default value of
eId
andeName
, but still the fields get initialized to default values. Is CLR doing this?
Yes.
For classes, the memory allocator zeroes out the memory before the constructor is executed.
For structs, the runtime allocates a blank struct from the short-lived store, passes a reference to the temporary variable as this
for the constructor, and then copies the value to the final destination. Note however that there are cases where the compiler and runtime can determine that the copy step can be elided without introducing a semantic change in the program.
Upvotes: 4
Reputation: 4352
Class member variables that are set in the class definition are set before the constructor with default values. If you want, you can easily reset that default values in the constructor. Constructor is mandatory for class. If you are not created any constructor for the class the compiler will create the parameter-less constructor automatically. The automatically created constructor will not initialize the class member variables.
.NET has two data types (Value type and Reference type). Internally these two data types has its own default value. (Mostly reference types has default value as null). In your program you have used int and string data types. Int has '0' as the default value and string has 'Null' as default value. If you are not initialize the variable it will automatically takes the default value and process it.
Default values for value data types : Default Values Table
Upvotes: 0
Reputation: 233150
All values and objects in .NET have default values. If you don't assign an explicit value, the default value will be used.
null
Guid.Emtpy
)Since you don't initialize your fields with values, they get the default values.
Upvotes: 5