C# variable initialization is another example of C# emphasizing safety. Simply put, the C# compiler requires a variable to be initialized with some initial value before it can be referenced in an operation. Most modern compilers flag uninitialized variables as warnings, but the C# compiler treats it as an error. This prevents us from accidentally picking up garbage values from memory left over by other programs.
There are two methods in C# variable initialization to ensure that a variable is initialized before it is used:
- If a variable is a field in a class or structure and is not explicitly initialized, its value is set to a default when the variable is created:0(Classes and structures are discussed later.)
- Local variables of a method must be explicitly initialized in code before their values can be used in statements. In this case, initialization is not performed when the variable is declared, but the compiler checks all possible paths through the method, and if it detects that a local variable's value is used before initialization, it generates an error.
C#'s approach is the opposite of C++'s approach. In C++, the compiler leaves it to the programmer to ensure variables are initialized before use, while in Visual Basic, all variables automatically have their values set to0。
Analysis of C# Variable Initialization Examples
For example, in C#, the following statement cannot be used:
public static int Main(){ int d; Console.WriteLine(d); // Error! Must be initialized before use }Note that this code demonstrates how to define Main() so that it returns data of type int instead of void.
When compiling this code, you will get the following error message:
Use of unassigned local variable 'd'
Consider the following statement:
Something objSomething;
In C++, the above code creates an instance of the Something class on the stack. In C#, this line of code only creates a reference for a Something object, but this reference does not yet point to any object. Calling a method or property on this variable will cause an error.
To instantiate a reference object in C#, you need to use the new keyword. As mentioned above, create a reference, and use the new keyword to point that reference to an object stored on the heap:
objSomething = new Something();
Original URL: https://www.cnblogs.com/shiguangshuo/p/4842144.html