Explicit assignment of null
Unassigned members are automatically initialized to their default values (which is the null reference in the case for string
).
Unassigned local variables are not assigned any value and trying to access a possibly unassigned variable will give a compile error.
The reason why explicit assignment is required is quite simple. This often a source of errors when people try to use unassigned/uninitialized variables.
By forcing the developer to do this, it eliminates errors which happen when the developer forgets to initialize the variable. And by initializing it, you're in control of it.
It's a good thing really! I dunno how often I had uninitialized or undefined variables in some of the scripting languages which took quite some time to be found ^^
If you have an unassigned local value, you are quite likely doing something stupid. Worse of all you are doing the sort of stupid thing that smart people can do in the heat of the moment, (everyone does something stupid every day).
Unlike some things that result in warnings, there's no possible advantage of using an unassigned value in a particular remarkable case.
The only cost difference between allowing an unassigned local or assuming a particular value, is a few keystrokes (normally
= null;
at most it could be= default(SomeType);
Banning such constructs is heavy on pros and low on cons. There's no technical reason why the language couldn't have been designed to allow unassigned locals, but the benefits of banning outweigh the disadvantages.
Have a look at the spec: 5.3 Definite assignment
Definite assignment is a requirement in the following contexts:
A variable must be definitely assigned at each location where its value is obtained.
s1 and s2 are initially unassigned (5.3.1 Initially assigned variables), but only s2 is considered definitely assigned at a given location, [because] all possible execution paths leading to that location contain at least one of the following:
- A simple assignment (Section 7.13.1) in which the variable is the left operand.
As you can see, null is irrelevant in this context. Important is the assignment itself, but not the value.