Structure in C#

A structure is a value type, means it stores on stack. So there is no overhead to maintain the stack and heap both. Structure does not require a separate reference variable. Its syntax is similar to a class.

Struct is more efficient than class. All reference types are cleaned by garbage collector. Structures cannot inherit other structures or classes. A structure in C# can contain fields. These fields can be marked as private, public, internal. Please keep in mind that we can't initialize a field inside a structure. However we can use parameterized constructor to initialize the structure fields.  A structure can contain constructors (Parameterized), fields, methods, properties, indexers, operators, events, and nested types.

Structures are declared using the keyword struct.

Example

public struct Employee
    {
        public int EmpID;
        public string Name;
        public string Address;
    }


Important things regarding structs

  • Structs are value types.
  • It does not support inheritance.
  • You cannot define a default (parameterless) constructor for a struct.
  • You can define parameterized constructor in struct.
  • Structure can implement interface.

Example

using System;
namespace ConsoleApplication1
{
    public struct Employee
    {
        public int EmpID;
        public string empName;
        private string Address;          
        public Employee(int ID,string name, string add)
        {
            EmpID = ID;
            empName = name;
            Address = add;           
        }
        public void ShowData()
        {
            Console.WriteLine("Employee ID="+EmpID);
            Console.WriteLine("Employee Name=" + empName);
            Console.WriteLine("Employee Address=" + Address);           
        }
    }    
    class Program
    {        
      static void Main(string[] args)
      {
          Employee obj = new Employee(10,"Raj","USA");
          obj.ShowData();
          Employee emp;
         // error, must initialize first
         // Console.WriteLine("Employee Name=" + emp.empName);
          Console.ReadLine();
      }
    }
}


Let us take one more example that will help to understand the structure.

Example

using System;
namespace ConsoleApplication1
{
    struct StructValueType
    {
        public int x;
    }    
    class Program
    {        
      static void Main(string[] args)
      {
          StructValueType obj1;
          StructValueType obj2;
          obj1.x = 10;
          obj2.x = 20;
          Console.WriteLine("obj1.x = {0}, obj2.x = {1}", obj1.x, obj2.x);
          obj1 = obj2;
          obj2.x = 30;
          Console.WriteLine();
          Console.WriteLine("obj1.x = {0}, obj2.x = {1}", obj1.x, obj2.x);
          Console.ReadLine();
      }
    }
}


Output:
obj1.x = 10, obj2.x = 20
obj1.x = 20, obj2.x = 30

In the above code the structure variables obj1 and obj2 are still separate even though we have done obj1=obj2. Both are value types so they are not refer to each other.

If we replace the structure with class then output will be different. Because, in this case the obj1 and obj2 will be reference type. Obj1 will be refer to obj2.

obj1.x = 10, obj2.x = 20
obj1.x = 30, obj2.x = 30

Note that in the second line both value is 30.

Properties in the structure

We can create properties in the structure. In this example we will create a structure with members: a property, a method, and a private field.

Example

using System;
namespace ConsoleApplication1
{
    struct propertyStruct
    {
        private int  intVar ;
        public int initValue
        {
            get
            {
                return intVar;
            }
            set
            {
                if (value>0)
                    intVar = value;
            }
        }
        public void DisplayValue()
        {
            Console.WriteLine("Value is: {0}", initValue);
        }
    }
    class Program
    {        
      static void Main(string[] args)
      {
          propertyStruct obj = new propertyStruct();
          obj.initValue = 25;
          obj.DisplayValue();
          Console.ReadLine();
      }
    }
}

Important difference between Class and Structure

ClassStructure
Class is a reference typeStructure is value type
Object stored on the heap.Stored on the stack, and behave like simple data type.
Class can inherit the another classStructure does not support the inheritance.
Class can have the all types of constructorSupports parameterized constructors only.
Supports destructors also.Does not support destructors.
The member variable of class can be initialized directly.You cannot initialize instance field directly.
Class can be declared as abstractYou cannot mark structure as abstract.
class object cannot be created without using the new keyword
MyClass obj = new MyClass();
Structure object can be created without using the new keyword.
MyStruct obj;