Analysis of partial initialization and full Initialization instances of structure of struct in C

  • 2020-11-03 22:34:08
  • OfStack

This paper analyzes the partial initialization and complete initialization of structure (struct) in C# and shares them with you for your reference. The specific analysis is as follows:

Suppose there is such a value type as struct, as shown below:


public struct Size
{
    public int Length;
    public int Width;
    public int Area()
    {
      return Length*Width;
    }
}

1. Client, call method after initializing all struct fields


class Program
{
    static void Main(string[] args)
    {
      Size size;
      size.Length = 10;
      size.Width = 5;
      Console.WriteLine(size.Area());
      Console.ReadKey();
    }
}

Results: 50

2. Client, initialize part of struct field


class Program
{
    static void Main(string[] args)
    {
      Size size;
      size.Length = 10;
      Console.WriteLine(size.Area());
      Console.ReadKey();
    }
}

Result: Error, unassigned local variable used.
Visible: If you want to call any method on an struct instance, you need to initialize all fields of struct.

3. Client, initializes struct via constructor


class Program
{
    static void Main(string[] args)
    {
      Size size = new Size();
      Console.WriteLine(size.Area());
      Console.ReadKey();
    }
}

Results: 0
Here: Creating an instance with the struct constructor essentially assigns an initial value of 0 to all struct fields.

Conclusion:

Before calling the struct instance method, you must assign initial values to all fields of struct, which requires full initialization, and partial initialization is not allowed. Or through the "struct instance. Field name "assigns all fields explicitly, or default values to all fields through the struct constructor.

Hopefully, this analysis will be helpful in your C# programming studies.


Related articles: