CSharp - Type Creation Struct Creation

Introduction

A struct is a value type, whereas a class is a reference type.

You cannot create struct by extending another class or struct, it does not support inheritance.

All struct instance implicitly derives from System.ValueType.

A struct can have all the members a class can, except the following:

  • A parameterless constructor
  • Field initializers
  • A finalizer
  • Virtual members
  • Protected members

A struct is used to create value type.

During the assignment, the value of struct is copied rather than a reference.

The following code creates struct to represent a point. It has two member fields: x and y.

Demo

using System;
struct Point{
     public int x, y;
     public Point (int x, int y) { 
        this.x = x; this.y = y; 
     }/*from w w w.  j  av  a 2 s.c  o  m*/
}
class MainClass
{
   public static void Main(string[] args)
   {
         Point p1 = new Point ();       // p1.x and p1.y will be 0
         Point p2 = new Point (1, 1);   // p1.x and p1.y will be 1
         
         Console.WriteLine(p1.x);
         Console.WriteLine(p2.x);

   }
}

Result

The following code shows different ways to create structure instance.

Demo

using System;

struct MyStructure
{
    public int i;
    public MyStructure(int i)
    {/* www  . j av  a2  s  . c o  m*/
        this.i = i;
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyStructure myS1 = new MyStructure();//OK
        myS1.i = 1;
        Console.WriteLine(" myS1.i={0}", myS1.i);

        //Another way of using structure
        MyStructure myS2 = new MyStructure(10);//OK
        Console.WriteLine(" myS2.i={0}", myS2.i);

        //Another way of using structure
        MyStructure myS3;
        myS3.i = 100;
        Console.WriteLine(" myS3.i={0}", myS3.i);

    }
}

Result

Quiz