When creating an instance of a class, if you do not assign an initial value to the member variable before executing the constructor, the C# compiler defaults to each member variable to its default value.
If the variable is a local variable of the method, the compiler will think that the code must set a value to the displayed variable before using it. Otherwise, an error of "Unassigned local variables are used".
For other cases, the compiler will initialize the variable to the default value when creating the variable.
1. For integer, floating point, and enumeration types (numerical), the default value is 0 or 0.0.
2. The default value of character type is \x0000.
3. The default value of Boolean type is false.
4. The default value of the reference type is null.
If an initial value (int i=10;) is specified for the sound time variable, then this value is used to initialize the variable.
Although the C# compiler sets the default type for each type, as an object-oriented design principle, we still need to initialize the variables correctly. In fact, this is also recommended by C#. Failure to initialize variables will cause the compiler to issue a warning message. We cannot assign initial values to all member variables. Of course, if we assign values, it may not necessarily meet our requirements. Because when we use it, it is possible to change our initial value. Then we need to use the constructor to initialize our member variables.
// The system will assign default values to member variables that have not been assigned to the constructor
using System;
public class Dog
{
public string name;
public int age;
public static void Main()
{
Dog myDog = new Dog();
("myDog's name is "{0}", and its age is {1}.", , );
}
}
In the above program, when the object myDog is created, the default constructor will be called. All fields are assigned to a default value.
The output result is:
The name of myDog is "", and the age is 0.
Although this feature can avoid compilation errors, it violates the "assign first, then use" principle of variables. These "harmless" default values are easy to produce difficult-to-identify errors. It is recommended to assign values to all member variables in the constructor as much as possible.