C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Struct

In C#, a struct (short for "structure") is a value type that can be used to group related variables, similar to a class. However, unlike classes, structs are stored on the stack, which makes them more efficient for small, short-lived objects. In this tutorial, we'll cover the basics of working with structs in C#.

  • Defining a struct

To define a struct, use the struct keyword, followed by the name of the struct and its body enclosed in curly braces:

struct Point
{
    public int X;
    public int Y;
}

Structs can have fields, properties, methods, and even constructors. However, they cannot have destructors or inherit from other structs or classes.

  • Creating an instance of a struct

To create an instance of a struct, you can use the new keyword, followed by the struct's name and any required constructor arguments:

Point point1 = new Point();

Alternatively, you can create an instance without using the new keyword. In this case, you must assign values to all fields before you can use the instance:

Point point2;
point2.X = 10;
point2.Y = 20;
  • Initializing fields and properties

You can initialize fields and properties directly within the struct definition, or you can use constructors:

struct Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
}

Point point = new Point(5, 10); // Initializes a Point instance with X = 5 and Y = 10
  • Adding methods

Structs can have methods, just like classes:

struct Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public double DistanceToOrigin()
    {
        return Math.Sqrt(X * X + Y * Y);
    }
}

Point point = new Point { X = 3, Y = 4 };
double distance = point.DistanceToOrigin(); // 5.0
  • Implementing interfaces

Structs can implement interfaces:

public interface IShape
{
    double GetArea();
}

struct Square : IShape
{
    public int SideLength { get; set; }

    public double GetArea()
    {
        return SideLength * SideLength;
    }
}
  • Limitations
  • Structs cannot have destructors.
  • Structs cannot inherit from other structs or classes.
  • Structs cannot be used as a base for other structs or classes.
  • Structs have a default parameterless constructor that initializes all fields to their default values. You cannot define your own parameterless constructor.

In this tutorial, we covered the basics of working with structs in C#. Structs are useful for grouping related variables and can have fields, properties, methods, and constructors. They are stored on the stack, which makes them more efficient for small, short-lived objects. However, structs have some limitations compared to classes, so choose the appropriate type based on your needs.

  1. How to use structs in C#

    Structs in C# are lightweight data types that represent a simple aggregate of data.

    public struct Point
    {
        public int X;
        public int Y;
    }
    
    Point origin = new Point();
    origin.X = 0;
    origin.Y = 0;
    
  2. Structs vs. classes in C#

    Structs and classes are both used to define custom types, but they differ in how they handle memory and data.

    // Struct example
    public struct Point { public int X; public int Y; }
    
    // Class example
    public class PointClass { public int X; public int Y; }
    
  3. Defining and declaring structs in C#

    Define a struct using the struct keyword and declare instances like other variables.

    public struct Book
    {
        public string Title;
        public string Author;
    }
    
    Book myBook;
    
  4. Structs and value types in C#

    Structs are value types, meaning they are stored directly where they are declared, not in a separate heap memory.

    struct Temperature
    {
        public double Celsius;
    }
    
    Temperature summerTemp;
    summerTemp.Celsius = 30.0;
    
  5. When to use structs vs. classes in C#

    Use structs for small, lightweight, and frequently copied data. Classes are suitable for more complex scenarios.

    // Struct example
    struct Point { public int X; public int Y; }
    
    // Class example
    class PointClass { public int X; public int Y; }
    
  6. Structs and memory allocation in C#

    Structs are typically allocated on the stack, providing better performance for small data structures.

    struct Measurement
    {
        public double Value;
        public string Unit;
    }
    
    Measurement weight;
    
  7. Nested structs in C#

    Structs can be nested within other structs or classes for better organization.

    struct Address
    {
        public string Street;
        public string City;
    
        public struct Coordinates
        {
            public double Latitude;
            public double Longitude;
        }
    }
    
  8. Initializing and working with structs in C#

    Initialize a struct using the default constructor or parameterized constructor.

    struct Point
    {
        public int X;
        public int Y;
    
        public Point(int x, int y)
        {
            X = x;
            Y = y;
        }
    }
    
    Point p = new Point(5, 10);
    
  9. Structs and immutability in C#

    Structs are inherently immutable if their fields are readonly.

    public readonly struct ImmutableStruct
    {
        public readonly int Value;
    
        public ImmutableStruct(int value)
        {
            Value = value;
        }
    }
    
  10. Copying and passing structs in C#

    Structs are copied by value, and passing them to methods involves passing a copy.

    struct Person
    {
        public string Name;
        public int Age;
    }
    
    void ModifyPerson(Person person)
    {
        person.Age = 30; // Does not modify the original struct
    }
    
  11. Structs and the heap vs. stack in C#

    Structs are often allocated on the stack, providing better performance compared to classes that are allocated on the heap.

    struct Point { public int X; public int Y; }
    Point stackPoint = new Point();
    
  12. Structs and interfaces in C#

    Structs can implement interfaces, allowing them to define a contract for behaviors.

    public interface IDrawable
    {
        void Draw();
    }
    
    public struct Circle : IDrawable
    {
        public void Draw()
        {
            // Implementation
        }
    }