Visual Studio null reference warning - why no error?

百般思念 提交于 2020-01-03 14:02:39

问题


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?


回答1:


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.




回答2:


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



回答3:


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).




回答4:


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.



来源:https://stackoverflow.com/questions/1413210/visual-studio-null-reference-warning-why-no-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!