In C#, method parameters can be categorized into value types and reference types based on how the data is passed to the method. Understanding the difference between them is crucial because it determines how changes to the parameter inside the method affect the original data.
Value Types Parameters
By default, C# passes method parameters by value. This means that when you pass a value-type parameter to a method, the method gets a copy of the value, and any changes to the parameter inside the method do not affect the original variable outside the method.
Note: Value types include simple types like int, double, char, and struct types.
Example:
using System;
public class ProgramExample
{
public int IncrementByOneNumber(int number)
{
return number = number+1;
}
public static void Main()
{
ProgramExample pe = new ProgramExample();
int result = pe.IncrementByOneNumber(10);
Console.WriteLine("The result is: " + result); // Output: The result is: 11
}
}
Output:
Reference Types Parameters
A reference type does not store the actual data directly; instead, it stores a reference (or memory address) pointing to the actual data. When you pass a reference type to a method, the reference is passed, meaning changes to the parameter inside the method will affect the original object outside the method.
Characteristics of Reference Types:
1. Stores a reference to the data (memory address).
2. When passed to methods, the reference to the data is passed (pass-by-reference).
3. Includes types like class, string, array, delegate, and object.
Example:
using System;
public class Employee
{
public string Name { get; set; }
}
public class ProgramExample
{
public void ChangeName(Employee emp)
{
emp.Name = "John"; // Modifies the original object
}
public static void Main()
{
Employee p = new Employee { Name = "Tom" };
ProgramExample program = new ProgramExample();
// Pass the object 'p' to the method
program.ChangeName(p);
// The 'Name' property of the original object 'p' has changed
Console.WriteLine("Name is: " + p.Name); // Output: John
}
}
Output: