C members of the different types of default values of the variables field

Transfer from:

Create an instance of the class before the constructor is executed, if you do not have the initial value given to the member variables, C # compiler default every member variable is initialized to the default value.

If the variables are local variables of the method, the compiler will set a value before the variable, the code must give it displayed. “Use of unassigned local variable” error will occur.

In other cases, the compiler will create a variable, the variable is initialized to the default value.
1 for integer, floating point, enumerated types (numeric), the default value of 0 or 0.0.
2, the default value of the character type \ x0000.
3, Boolean default value is false.
4, reference types, the default value is null.

If the sound when the variable, it specifies the initial value (int i = 10 ;), then this value is used to initialize the variable.

Although the C # compiler for each type are set to the default type, but as the object-oriented design principles, we still need to be properly initialized variables. In fact, the C # which is the recommended practice, there is no variable initialization causes the compiler to issue a warning message. We can not all member variables to the initial value given, of course, is assigned a value, it did not necessarily meet our requirements. In use, it is possible to change the initial value. Then we will have with the constructor to initialize the member variables.

/ / For member variables are not assigned in the constructor assign a default value

using System;
public class Dog
public string name;
public int age;
public static void Main ()
The Dog the myDog = new Dog ();
The Console.WriteLine (“the myDog name” {0} “, age for {1}.” MyDog.name myDog.age);
The above procedure, when create object myDog, is called the default constructor. All fields are assigned to a default value.
the name of myDog “age of 0.

This feature can avoid compilation errors, but contrary to the variable assignment after use “principle, these” harmless “default values ??can easily lead to hard-to-identify errors, it is recommended that as much as possible to all members in the constructor variable.

Add a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!