C# struct Constructor

In this chapter you will learn:

  1. Use method to init struct member variables
  2. Struct constructor with parameters

Default constructor

If you define a constructor for a struct you must use the constructor to initialize all fields.


using System;/* w w  w  .j av  a 2 s  .  co  m*/


public struct Simple {

  public  int i;
  private string s;
  

  public void init( ) {
    i = 10;
    s = "Hello";
  }
  
}



public class MainClass {

  public static void Main( ) {

    Simple simple = new Simple();
  
    simple.init( );
    
  }
}

struct cannot have the field initializer.

The code above generates the following result.

Example 2


using System;/*from w  ww .j  av a 2  s .  c o  m*/

struct Point
{
   public int x;
   public int y;
   public Point(int a, int b) 
   {
      x = a;
      y = b;
   }
}

class MainClass
{
   static void Main()
   {
      Point p1 = new Point();
      Point p2 = new Point(5, 10);

      Console.WriteLine("{0},{1}", p1.x, p1.y);
      Console.WriteLine("{0},{1}", p2.x, p2.y);
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Object Identity vs. Value Equality
  2. Value type equality (default behavior)
  3. override Equals method
Home »
  C# Tutorial »
    C# Types »
      C# Struct
C# Structs
C# Struct Instances vs. Class Instances
C# struct Constructor
C# struct equality
C# Generic struct