Struct Constructors
Collapse the table of content
Expand the table of content

Struct Constructors

Visual Studio .NET 2003

Struct constructors are similar to class constructors, except for the following differences:

  • Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
  • A struct cannot have an initializer in the form: base (argument-list).


The following is an example of a constructor using two arguments for the Point struct.

// Structctor1.cs
using System;

public struct Point 
   public int x, y;
   // Constructor:
   public Point(int x, int y) 
      this.x = x;
      this.y = y;
   // Override the ToString method:
   public override string ToString()
      return(String.Format("({0},{1})", x, y));   

class MainClass 
   static void Main()  
      // Initialize two points:
      Point p1 = new Point();
      Point p2 = new Point(10,15);

      // Display the results using the overriden ToString method:
      Console.WriteLine("Point #1 (default initialization): {0}", p1);
      Console.WriteLine("Point #2 (explicit initialization): {0}", p2);


Point #1 (default initialization): (0,0)
Point #2 (explicit initialization): (10,15)

For more information on structs, see struct and the Structs Tutorial.

For a complete comparison between structs and classes, see 11.3 Class and struct differences.

See Also

Constructors and Destructors | Class Constructors

© 2015 Microsoft