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?
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With