views:

247

answers:

4

I've noticed something peculiar about Visual Studio. First, try typing this (C#) somewhere in a function:

class Foo  
{  
    public void Bar()  
    {  
        string s;
        int i = s.Length;
    }
}

Now, right away it will mark the s in s.Length as an error, saying "Use of unassigned local variable 's'". On the other hand, try this code:

class Foo  
{  
    private string s;
    public void Bar()  
    {  
        int i = s.Length;
    }
}

It will compile, and underline the s in private string s with a warning, saying "Field 'Foo.s' is never assigned to, and will always have its default value null".

Now, if VS is that smart and knows that s will always be null, why is it not an error to get its length in the second example? My original guess was, "It only gives a compile error if the compiler simply cannot complete its job. Since the code technically runs as long as you never call Bar(), it's only a warning." Except that explanation is invalidated by the first example. You could still run the code without error as long as you never call Bar(). So what gives? Just an oversight, or am I missing something?

+7  A: 

The first example (the error) is an example of the Compiler's definite-assignment tracking and that is only applied to local variables. Due to the limited context, the compiler has an airtight grip on this situation. Note that s is not null, it is undefined.

In the second example, s is a field (and defaults to null). There is no compiler error, but it will always be caught at runtime. This particular case could be trapped but this kind of error is not in general detectable by the compiler.
For example, you could add a method Bar2() that assigns a string to s but call it later than Bar(), or not at all. That would eliminate the warning but not the runtime error.

So it is by design.

Henk Holterman
A: 

The only guess I can make is that in the second example, s could be changed via reflection (using BindingFlags.Private to access the private member).

Robert Fraser
A: 

In first sample s is a local variable and compiler can easialy check that s varible wasn't assigned before it's used.

In the second one, s is a global variable and it's possible that it was initialized somewhere else in a class.

Vadim
s is not global, it is an instance-field.
Henk Holterman
+3  A: 

For the second example the code is valid it just might not run correctly. Here are several cases in which this program could execute "successfully"

  • The compiler is not 100% correct. It is possible for "s" to have a non-null value if an instance is modified via reflection.
  • The program can execute without error if the method Bar isn't ever called
  • This program could be a test program which is triggering a NullReferenceException for testing reasons
JaredPar