How to use constructor for struct

Default constructor

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


using System;//www.  ja  v  a  2  s .c  o  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 w  w. j ava2  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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor