Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assign value to string before comparing, when default is null

Tags:

c#

asp.net

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?

like image 619
GirishK Avatar asked Oct 16 '12 11:10

GirishK


2 Answers

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;
like image 60
Henk Holterman Avatar answered Nov 04 '22 00:11

Henk Holterman


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.

like image 30
Tim Schmelter Avatar answered Nov 03 '22 22:11

Tim Schmelter