Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio null reference warning - why no error?

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?

like image 251
Tesserex Avatar asked Sep 11 '09 20:09

Tesserex


2 Answers

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.

like image 156
Henk Holterman Avatar answered Oct 09 '22 04:10

Henk Holterman


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
like image 45
JaredPar Avatar answered Oct 09 '22 03:10

JaredPar