GirishK
GirishK

Reputation: 1963

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

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?

Upvotes: 5

Views: 349

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273294

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;

Upvotes: 7

Tim Schmelter
Tim Schmelter

Reputation: 460168

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.

Upvotes: 2

Related Questions