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?