articles

home / developersection / articles / understanding struct in c#

Understanding struct in C#

Understanding struct in C#

Anubhav Kumar 1047 22-Apr-2025

In C#, struct (short for structure) is a value type used to store related data under a single unit. It's similar to a class, but with some key differences in behavior and use cases.

What is a Structure?

A structure is a user-defined type that groups different variables under one name. Structs are best used for small data containers that don’t require inheritance or complex behaviors.

struct StructName
{
    // Fields
    public int field1;
    public string field2;

    // Constructor
    public StructName(int f1, string f2)
    {
        field1 = f1;
        field2 = f2;
    }

    // Methods
    public void Display()
    {
        Console.WriteLine($"Field1: {field1}, Field2: {field2}");
    }
}

Example: Defining and Using a Struct

using System;

struct Employee
{
    public int ID;
    public string EmployeeName;

    public Employee(int id, string name)
    {
        ID = id;
        EmployeeName = name;
    }

    public void Display()
    {
        Console.WriteLine($"ID: {ID}, Name: {EmployeeName}");
    }
}

class Program
{
    static void Main()
    {
        Employee emp1 = new Employee(101, "Alice");
        emp1.Display();
    }
}

Output: 

ID: 101, Name: Alice

Struct vs Class

Feature struct class
Type Value type Reference type
Memory allocation Stack Heap
Inheritance Not supported Supported
Performance Faster for small data Suitable for complex models
Null assignment Not allowed (unless nullable) Allowed
Default constructor Not allowed (you define it) Provided automatically

When to Use Struct?

Use a struct when:

  1. You’re representing simple objects (like a point, color, coordinate).
  2. You want value semantics (copying data instead of references).
  3. You don’t need inheritance or polymorphism.

Additional Notes

  1. Structs can implement interfaces, but cannot inherit from another struct or class.
  2. You can use Nullable<T> or T? with structs if you want to allow null values.
  3. Structs are copied by value, not by reference. So changes made to one copy don't affect the original.

Mini Quiz

struct Point {
    public int X, Y;
}

Point p1 = new Point();
p1.X = 5;
Point p2 = p1; // Now it assign 
p2.X = 10;
Console.WriteLine(p1.X);

Summery

Concept Explanation
struct keyword Defines a structure
Value type Stored on the stack
No inheritance Cannot inherit from classes or other structs
Lightweight Best for small, immutable data
Copy behavior Passed and assigned by value

 

Read More

Structure types - C# reference


c# c# 
Updated 22-Apr-2025
Anubhav Kumar

Student

The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By