Hi Guys
NP54 Declaring different way
I wish to know is there any difference in declaring a variable in different way for example:
int x;
Same variable is declared in different way
int x = new int();
The article in the following website give rise to this question. Anyone knows please explain.
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx
Thank you
public int ReturnValue()
{
int x = new int();
x = 3;
int y = new int();
y = x;
y = 4;
return x;
}
Posted Oct 23, 2007, 2:34 PM
Thank you very much for the explanation, Alan
AlanPosted Oct 23, 2007, 11:01 AM
Although the 'int' type (or System.Int32 to give it its full title) has a default parameterless constructor, it is seldom used because all it does is create a new int with the value of zero.
So, these lines do exactly the same thing:
int x = 0;
int x = new int();
However, this line (within a method or property) is different:
int x;
What that does is create a new local 'int' variable called 'x' but no value is assigned to it. The compiler therefore regards it as unassigned until you do assign a value to it. Consequently, the compiler produces an error if you try (or you appear to be trying) to use that variable without giving it a value first.
On the other hand if the same line is used as the declaration of a field, rather than a local variable, the compiler will allow it because (by default) all int fields are given a value of zero.