The CLR provides a strong guarantee that local variables are initialized with a default value. But this guarantee has limitations. Its ability to recognize blocks of regions inside the method body is lacking. They disappear after the compiler translates the code into IL. Scope is a language construct that has no parallel in the CLI and cannot be expressed in IL.
You can see that this is happening incorrectly in a language such as VB.NET. This contrived example shows the behavior:
Module Module1 Sub Main() For ix = 1 To 3 Dim s As String If ix = 2 Then s = "foo" If s Is Nothing Then Console.WriteLine("null") Else Console.WriteLine(s) Next Console.ReadLine() End Sub End Module
Conclusion:
null foo foo
Or, in other words, the local variable s was initialized only once and after that it stores the value. Of course, this gives the ability to create mistakes. The VB.NET compiler generates a warning for it and has simple syntax to avoid it (like new). A managed language such as C ++ / CLI has the same behavior, but does not generate diagnostics at all. But the C # language gives a stronger guarantee, it generates an error.
This rule is called a "specific task." The exact rules are described in detail in the C # Language Specification, chapter 5.3.3
A certain assignment check has its limitations. It works well for local variables, since their scope is very limited (private to the method body), and you cannot get to them using Reflection. It is much more difficult to do with the fields of the class, this requires an analysis of the entire program, which may be required to achieve what the compiler can see. Like code in another assembly. This is why the C # compiler can only warn about this, but cannot reject code outside of the law.
source share