Why does changing a number inside a method not change the original? The answer lies in how value types are passed!
Why Passing value types to methods in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a number and you want to double it by sending it to a method. You try to change the number inside the method, but when you check the original number, it stays the same.
This happens because when you send a value type like a number to a method, the method gets a copy, not the original. So any changes inside the method don't affect the original number. Doing this manually by returning and reassigning values is slow and confusing.
Passing value types to methods lets you work with copies safely. You can decide if you want to change the copy or use special ways to change the original. This keeps your code clear and avoids unexpected changes.
void Double(int num) { num = num * 2; }
int x = 5;
Double(x);
// x is still 5void Double(ref int num) { num = num * 2; }
int x = 5;
Double(ref x);
// x is now 10You can control how data is passed and changed in your program, making it safer and easier to understand.
Think of passing a score to a method that calculates bonus points. If you want the original score updated, you use passing by reference; otherwise, you keep the original safe.
Value types are copied when passed to methods.
Changes inside the method don't affect the original unless passed by reference.
This helps avoid accidental changes and keeps code predictable.