A Brief Discussion on Variable Initialization in C
Category Programming Technology
Variable initialization in C# is another example of its emphasis on safety. Simply put, the C# compiler requires variables to be initialized with some initial value before they can be referenced in operations. Most modern compilers mark uninitialized variables as warnings, but the C# compiler treats them as errors. This prevents us from inadvertently obtaining garbage values from leftover memory of other programs.
There are two methods in C# to ensure that variables are initialized before use:
If the variable is a field in a class or structure, and it is not explicitly initialized, its value defaults to 0 when created (classes and structures will be discussed later).
Local variables in methods must be explicitly initialized in the code before their values can be used in statements. At this point, initialization is not done at the time of declaration, but the compiler checks all possible paths through the method and generates an error if it detects that a local variable is used before being initialized.
C#'s approach is opposite to that of C++, where the compiler leaves it to the programmer to ensure variables are initialized before use, and in Visual Basic, all variables are automatically set to 0.
Example Analysis of Variable Initialization in C
For instance, the following statement cannot be used in C#:
Note in this code, how Main() is defined to return an int type data 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 to a Something object, but this reference does not point to any object. Calling methods or properties on this variable will result in an error.
Instantiating a reference object in C# requires the use of the new keyword. As mentioned, creating a reference and using the new keyword to point it to an object stored on the heap:
objSomething = new Something();
>
Original Source: https://www.cnblogs.com/shiguangshuo/p/4842144.html
** Click to Share Notes
-
-
-