0
0
C Sharp (C#)programming~5 mins

Struct declaration and behavior in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A struct lets you group related data together in one place. It is a simple way to create your own data type.

When you want to represent a small group of related values, like a point with X and Y coordinates.
When you need a lightweight object that holds data but does not require inheritance.
When you want to avoid the overhead of a class for simple data containers.
When you want to pass data by value instead of by reference.
When you want to create a type that behaves like a basic data type.
Syntax
C Sharp (C#)
struct StructName
{
    // fields, properties, methods
}

A struct is declared with the struct keyword followed by its name.

Structs are value types, so they are copied when assigned or passed around.

Examples
This defines a struct named Point with two integer fields: X and Y.
C Sharp (C#)
struct Point
{
    public int X;
    public int Y;
}
This struct Rectangle has fields and a method to calculate the area.
C Sharp (C#)
struct Rectangle
{
    public int Width;
    public int Height;

    public int Area() => Width * Height;
}
Creating an instance of Point and setting its fields.
C Sharp (C#)
Point p1 = new Point();
p1.X = 5;
p1.Y = 10;
Sample Program

This program shows how structs are copied by value. Changing p2 does not affect p1.

C Sharp (C#)
using System;

struct Point
{
    public int X;
    public int Y;

    public void Display()
    {
        Console.WriteLine($"Point is at ({X}, {Y})");
    }
}

class Program
{
    static void Main()
    {
        Point p1 = new Point();
        p1.X = 3;
        p1.Y = 4;
        p1.Display();

        Point p2 = p1; // copy of p1
        p2.X = 10;
        p2.Y = 20;

        p1.Display();
        p2.Display();
    }
}
OutputSuccess
Important Notes

Structs do not support inheritance but can implement interfaces.

Because structs are value types, they are stored on the stack, which can be faster for small data.

Be careful when modifying copies of structs, as changes do not affect the original.

Summary

Structs group related data into one simple type.

They are value types and copied when assigned or passed.

Use structs for small, simple data containers without inheritance.