C different types of member variables of field default values are introduced

  • 2020-06-03 08:11:02
  • OfStack

When creating an instance of a class, the C# compiler, by default, initializes each member variable to its default value before executing the constructor.

If a variable is a local variable of a method, the compiler assumes that the code must set 1 value to its display before using the variable. Otherwise, an "unassigned local variable is used" error occurs.

In other cases, the compiler initializes a variable to its default value when it is created.
1. For integer, floating point, and enumerated types (numeric), 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 reference type is null.

If the sound time variable is initialized with an initial value (int i=10;) , the 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 what C# recommends, and not initializing a variable causes the compiler to issue a warning. We can't assign an initial value to all of the member variables, but if we do, it doesn't have to be 1. Because when we use it, it's possible to change our initial values. Then we need to use the constructor to initialize our member variables.


//  Default values are assigned to member variables that are not assigned in the constructor 
using System;
public class Dog
{
    public string name;
    public int age;
    public static void Main()
    {
        Dog myDog = new Dog();
        Console.WriteLine("myDog The name is" {0} ", age is {1} . ", myDog.name, myDog.age);
    }
}

In the above program, the default constructor is called when the object myDog is created. All fields are assigned a default value.
The output result is:
myDog's name is "" and his age is 0.

While this feature avoids compilation errors, it violates the "assign first, use later" principle of variables, which are "harmless" defaults and are prone to unrecognizable errors. It is recommended to assign values to all member variables in constructors whenever possible.


Related articles: