Reputation: 29
using System;
class Test
{
string name;
int num1, num2;
public Test()
{
num1=10;
num2=20;
}
public void Show()
{
Console.WriteLine(num1+num2);
Console.WriteLine(name);
}
}
class TestDemo
{
static void Main()
{
Test ob = new Test();
ob.Show();
}
}
Confusion:
The Complete Reference C# 3.0 says that a default constructor will not be called if you define your own constructor. I did that thing, but left the string variable without initializing it with my defined constructor. Now according to above concept the string variable is not initialized and no default constructor will run to give it a default value because I have defined my own.
So, why it does not show an error, that string is not initialized with any value or something similar. Doesn't it show that it has been assigned a value from somewhere [default constructor of compiler]?
Upvotes: 1
Views: 428
Reputation: 9458
Your constructor
public Test()
{
num1=10;
num2=20;
}
is same as
public Test()
{
}
If you want to initialize num1
and num2
, you can do it as below:
private int num1, num2; //public fields are not recommended
public Test(int numberOne, int numberTwo)
{
num1 = numberOne;
num2 = numberTwo;
}
and you can do initialization as below:
Test ob = new Test(10,20);
Upvotes: -1
Reputation: 1500525
There's no such thing as an "uninitialized" field (whether static or instance). All fields are initialized with a default value (null for reference types, the "natural zero" for value types).
The compiler will give you a warning if you include a readonly
field which isn't assigned a value in the constructor, as then it will always have that default value - but it's still initalized.
The compiler can only spot when a local variable is used without being definitely assigned. That's because the compiler has a lot more information about control flow within a method than between methods within a class. If you have one method which assigns a value to a field and another which fetches the value from the field, there's no way for the compiler to know which will be called first - whereas the rules of definite assignment allow it to analyze a method to spot potential flows where a variable is read without having been assigned a value first.
None of this really has anything to do with default constructors, by the way. The compiler only provides a default constructor if you don't provide any constructors at all - so in your Test
class, there's no default constructor as such, because you've provided your own parameterless constructor. Even if the compiler did provide a default constructor, it would be exactly equivalent to:
public Test() {}
... the fields would still just have their default values.
Upvotes: 3