C # langauge requires all variables to be assigned before they are read. Local variables are considered initially unassigned, while fields, array elements, etc. They are considered initially assigned to their default values. (Which for the reference type is null.)
There are no technical reasons why we could not treat local variables as originally assigned to their default values and discard all specific assignment checks. This is because using an unassigned local default value is (1) bad coding practice and (2) a very likely source of annoying errors. If you want to explicitly assign local variables before using them, we do not allow the user to use bad practice and exclude a whole class of errors that you then do not have to debug.
Also consider the following:
while(whatever) { int i; print(i); i = i + 1; }
Do you expect me to keep its value in all cycles of the cycle or to initialize it to zero every time? Forcing you to explicitly initialize it, the question becomes meaningless, and this difference does not make any difference.
(In addition, in the above case, there is a slight potential performance optimization, since the compiler can reuse the variable without having to generate code to clear its contents, because the compiler knows that you will clear the contents.)
I don’t know how to answer your second question, because I don’t know what you mean by “work”. Can you tell me how to assign "int x = 123;" working? Once I know what you mean by “work,” I can describe how nulling a variable of a reference type works.
Eric Lippert
source share