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

Passing value types to methods in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Passing value types to methods lets you send a copy of data so the original stays safe and unchanged.

When you want to give a method a number or small data to work with without changing the original.
When you want to keep your original data safe from accidental changes inside methods.
When you want to perform calculations or checks using a copy of the data.
When you want to pass simple data like integers, floats, or structs to a method.
Syntax
C Sharp (C#)
void MethodName(int value) {
    // use value inside method
}

// calling the method
MethodName(5);

The method receives a copy of the value, not the original variable.

Changes inside the method do not affect the original variable.

Examples
This method prints the number passed to it.
C Sharp (C#)
void PrintNumber(int number) {
    Console.WriteLine(number);
}

PrintNumber(10);
The method increases the copy of x, but the original x stays 5.
C Sharp (C#)
void Increase(int num) {
    num = num + 1;
    Console.WriteLine(num);
}

int x = 5;
Increase(x);
Console.WriteLine(x);
Sample Program

This program shows that the method gets a copy of the number. Changing it inside the method does not change the original.

C Sharp (C#)
using System;

class Program {
    static void DoubleValue(int value) {
        value = value * 2;
        Console.WriteLine($"Inside method: {value}");
    }

    static void Main() {
        int number = 10;
        Console.WriteLine($"Before method call: {number}");
        DoubleValue(number);
        Console.WriteLine($"After method call: {number}");
    }
}
OutputSuccess
Important Notes

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

Passing value types copies the data, so large structs might be slower to pass.

To change the original value, use ref or out keywords (advanced topic).

Summary

Passing value types sends a copy of the data to the method.

Changes inside the method do not affect the original variable.

This helps keep your original data safe and unchanged.