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

Value type copying behavior in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Value types hold their data directly. When you copy them, you get a new, separate copy of the data.

When you want to store simple data like numbers or small groups of related values.
When you want to avoid unexpected changes by having independent copies.
When you want fast copying without extra memory overhead.
When you want to pass data to methods without affecting the original.
When you want to understand how structs behave differently from classes.
Syntax
C Sharp (C#)
Type variable1 = value;
Type variable2 = variable1; // copies the value

Value types include int, double, bool, and structs.

Copying creates a new independent copy, so changing one does not affect the other.

Examples
Copying an integer creates a new value. Changing b does not change a.
C Sharp (C#)
int a = 5;
int b = a; // b is now 5
b = 10; // a is still 5
Copying a struct creates a new independent copy of its fields.
C Sharp (C#)
struct Point { public int X, Y; }
Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1; // copy
p2.X = 10; // p1.X is still 1
Sample Program

This program shows that changing the copy does not affect the original for both int and struct types.

C Sharp (C#)
using System;

struct Point
{
    public int X, Y;
}

class Program
{
    static void Main()
    {
        int num1 = 100;
        int num2 = num1; // copy value
        num2 = 200;

        Point pt1 = new Point { X = 5, Y = 10 };
        Point pt2 = pt1; // copy struct
        pt2.X = 50;

        Console.WriteLine($"num1 = {num1}, num2 = {num2}");
        Console.WriteLine($"pt1.X = {pt1.X}, pt2.X = {pt2.X}");
    }
}
OutputSuccess
Important Notes

Remember, value types store data directly, so copying duplicates the data.

Reference types behave differently; copying them copies the reference, not the data.

Summary

Value types hold data directly and copying them creates independent copies.

Changing a copied value type does not affect the original.

Common value types include int, bool, double, and structs.