ref Parameter in C#
Shahzad
Posted on April 3, 2024
In C#, the ref keyword is used to indicate that a method parameter is a reference parameter. Reference parameters allow you to pass a reference to a variable as an argument to a method, rather than passing a copy of the variable's value. This means that any changes made to the parameter within the method will affect the original variable outside the method as well.
Example
In below we have defined the syntax of ref method. The ref method have retrun type for example int, float or string and a methodName that can be any suitable name of the method and we have defined the parameter ref with the first ref keword then it will have any datatype for example int, string and parameter name for example referenceParameter in below syntax then we have defined the body of parameter where we used this ref parameter and will assigne a value to this ref parameter.
returnType methodName(parameters, ref dataType referenceParameter)
{
// Method body
// The method assigns a value to referenceParameter
// ...
}
Basic structure of ref parameter
Method Signature:
When defining a method that accepts a ref keyword, you specify the ref keyword before the parameter type in the method signature.
Argument Passing:
When calling the method, you must also use the ref keyword to indicate that you are passing a reference to a variable.
Example one with simple variable
In the below example we have private class Program and this Program class have Main entry method. In Main entry method we have defined SimpleWithRef method which does not have any return type and has a ref parameter of integer type x. In the body of SimpleWithRef method we have assigned a value to x variable. In reality we are modifying the existing value with new value. Outside the SimpleWithRef method we have declared a integer type x vaiable and assinged a 10 value to this x variable. We are printing a value of x variable before call of SimpleWithRef method. Which is 10 before call. After this we are calling SimpleWithRef function that must have ref keyword then a variable name x. After this we are again printing the value of x. Now you can monitored that the original value of x parameter has changed after it's call. Which is now become 30.
using System;
public class Program
{
public static void Main(string[] args)
{
void Simple(int y)
{
y = 40; //Not Modifies the original 'y' variable
}
void SimpleWithRef(ref int x)
{
x = 30; // Modifies the original 'x' variable
}
int x = 10;
Console.WriteLine("Before call x value is=" + x);
SimpleWithRef(ref x); // Calling the SimpleWithRef function
Console.WriteLine("After call x value is=" + x);
int y = 20;
Console.WriteLine("Before cal y value is=" + y);
Simple(y); // Calling the Simple function
Console.WriteLine("After call y value is=" + y);
}
}
Output
Before call x value is=10
After call x value is=30
Before cal y value is=20
After call y value is=20
Example two with classes
using System;
public class Program
{
public static void Main(string[] args)
{
Fruit objFruit = new Fruit(18, "WaterMelon", true);
int fieldPrice = objFruit.GetFruitPrice(); // Accessing a field fruit price
string fieldName = objFruit.GetFruitName(); // Accessing a field fruit name
bool fieldIsInMarket = objFruit.GetFruitIsInMarket(); // Accessing a field fruit is in market
Console.WriteLine("Fruit result before using ref keword");
Console.WriteLine("Fruit name: " + fieldName + " Fruit price:" + fieldPrice + " Is available in summer :" + fieldIsInMarket);
objFruit.SetFruit(ref objFruit.FruitPrice, ref objFruit.FruitName, ref objFruit.FruitIsAvialableInSummer);
Console.WriteLine("Fruit result after using ref keword without class");
Console.WriteLine("Fruit name: " + objFruit.FruitName + " Fruit price:" + objFruit.FruitPrice + " Is available in summer :" + objFruit.FruitIsAvialableInSummer);
objFruit.SetNewFruit(ref objFruit);
Console.WriteLine("Fruit result after using ref keword with class");
Console.WriteLine("Fruit name: " + objFruit.FruitName + " Fruit price:" + objFruit.FruitPrice + " Is available in summer :" + objFruit.FruitIsAvialableInSummer);
}
}
public class Fruit
{
// Fields (attributes or variables)
public int FruitPrice;
public string FruitName;
public bool FruitIsAvialableInSummer;
// Constructor
public Fruit(int price, string name, bool isAvailable)
{
FruitPrice = price;
FruitName = name;
FruitIsAvialableInSummer = isAvailable;
}
// Methods (functions or behaviors)
public int GetFruitPrice()
{
return FruitPrice;
}
public string GetFruitName()
{
return FruitName;
}
public bool GetFruitIsInMarket()
{
return FruitIsAvialableInSummer;
}
public void SetFruit(ref int FruitPrice, ref string FruitName, ref bool FruitIsAvialableInSummer)
{
FruitPrice = 28;
FruitName = "Orange";
FruitIsAvialableInSummer = false;
}
public void SetNewFruit(ref Fruit fruitChange)
{
fruitChange.FruitPrice = 23;
fruitChange.FruitName = "Mango";
fruitChange.FruitIsAvialableInSummer = true;
}
}
Output
Fruit result before using ref keword
Fruit name: WaterMelon Fruit price:18 Is available in summer :True
Fruit result after using ref keword without class
Fruit name: Orange Fruit price:28 Is available in summer :False
Fruit result after using ref keword with class
Fruit name: Mamgo Fruit price:23 Is available in summer :True
Example three with struct
using System;
public class Program
{
public static void Main(string[] args)
{
Point p1 = new Point(10, 20);
Point p2 = p1; // Copying p1 to p2
p2.SetValuePoint(ref p2);
Console.WriteLine($"p1: {p1}"); // Output: p1: (10, 20)
Console.WriteLine($"p2: {p2}"); // Output: p2: (30, 20)
}
}
public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
public override string ToString()
{
return $"({X}, {Y})";
}
public void SetValuePoint(ref Point p2)
{
p2.X = 30; // Modifying p2
}
}
Output
p1: (10, 20)
p2: (30, 20)
Why we use ref keyword?
1. Modifying the Original Value:
When you need to modify the original variable out side the scope of declaration of method.
2. Copying Large Structure Of Data
When you have need for passing a large structure of data from one location to another. You can pass this large data with ref kayword to get avoidance from copying of data after change in desired location.
3. Returing Multiple Values
When you have need of returning multiple value you can use ref keyword.
Summary
We can change the original value of a variable or class variable out the another class by ref keyword becasue ref keyword make a variable or class reference type.
In C#, list themselves are reference types. This means that when you pass a list to a method or assign it to another variable, you're passing the reference to the list, not the list itself. Any changes made to the list within the method or through the assigned variable will affect the original list. so we don't need to send a list to outside the class with ref keword.
In C#, structs are inherently value types, and you cannot directly change a struct to behave like a reference type but by using ref parameter you can change the value of the variable of struct.
Posted on April 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.