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

Value type vs reference type performance in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Understanding the speed difference between value types and reference types helps you write faster and more efficient C# programs.

When you want to store small data like numbers or points efficiently.
When you need to pass data quickly without extra memory use.
When you want to avoid slow memory access caused by references.
When you want to understand why some data types run faster than others.
When deciding between struct and class for your data design.
Syntax
C Sharp (C#)
struct MyValueType {
    public int Number;
}

class MyReferenceType {
    public int Number;
}

Value types store data directly and are usually faster for small data.

Reference types store a reference (like an address) to the data on the heap.

Examples
This is a value type example using a struct to hold coordinates.
C Sharp (C#)
struct Point {
    public int X;
    public int Y;
}

Point p = new Point { X = 5, Y = 10 };
This is a reference type example using a class to hold a name.
C Sharp (C#)
class Person {
    public string Name;
}

Person person = new Person { Name = "Anna" };
Sample Program

This program shows how changing a copy of a value type does not affect the original, but changing a reference type copy affects the original because both point to the same data.

C Sharp (C#)
using System;

struct MyValueType {
    public int Number;
}

class MyReferenceType {
    public int Number;
}

class Program {
    static void Main() {
        MyValueType val1 = new MyValueType { Number = 10 };
        MyValueType val2 = val1; // copies the value
        val2.Number = 20;

        Console.WriteLine($"val1.Number = {val1.Number}");
        Console.WriteLine($"val2.Number = {val2.Number}");

        MyReferenceType ref1 = new MyReferenceType { Number = 10 };
        MyReferenceType ref2 = ref1; // copies the reference
        ref2.Number = 20;

        Console.WriteLine($"ref1.Number = {ref1.Number}");
        Console.WriteLine($"ref2.Number = {ref2.Number}");
    }
}
OutputSuccess
Important Notes

Value types are stored on the stack, which is faster to access.

Reference types are stored on the heap, which can be slower due to extra memory management.

Use value types for small, simple data to improve performance.

Summary

Value types hold data directly and are faster for small data.

Reference types hold a pointer to data and can be slower due to memory access.

Understanding this helps you choose the right type for better program speed.