Why I always need to assign a value to string variable, before actually using it to compare. For ex: Some input - obj
string temp;
if (obj== null)
{
temp = "OK";
}
string final = temp;
I get compile time error - something like - cant use unassigned variable 'temp'. But string variable has default value as 'null', which I want to use. So why this is not allowed?
when default is null
The default is not null (or anything else) for a local variable. It's just unassigned.
You are probably thinking about a string field (a variable at the class level). That would be null
:
private string temp;
private void M()
{
if (obj== null)
{
temp = "OK";
}
string final = temp; // default tnull
}
But inside a method, just initialize with the value you need:
string temp = null;
Then assing null as default for your local variable:
string temp = null;
It's just a compiler hint that you might have forgotten to assign a value. By explicitely assigning null you're telling the compiler that you've thought about it.
C# Language specification v. 4.0 section 1.6.6.2 "Method body and local variables" states the following:
A method body can declare variables that are specific to the invocation of the method. Such variables are called local variables. ... C# requires a local variable to be definitely assigned before its value can be obtained.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With