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

Why Passing value types to methods in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Why does changing a number inside a method not change the original? The answer lies in how value types are passed!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
void Double(int num) { num = num * 2; }
int x = 5;
Double(x);
// x is still 5
After
void Double(ref int num) { num = num * 2; }
int x = 5;
Double(ref x);
// x is now 10
What It Enables

You can control how data is passed and changed in your program, making it safer and easier to understand.

Real Life Example

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.

Key Takeaways

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.