Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

ref Keyword in c#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In C#, the ref keyword is used to send and return references to and from Methods. Any change made to a value supplied by reference will be reflected because you are changing the deal at the address rather than the value itself. It can be used in the following scenarios:

  • To reference an argument and pass it to a method.
  • To create a method signature that returns a variable reference.
  • To declare a struct as a ref struct.
  • As a local example.

 

Recommended Topic -  singleton design pattern in c#

Example: Passing Value Type Variable

using System;

public class Program
{
public static void Main()
{
int num = 10000;
             
        // pass value type
        Example(num);
        Console.WriteLine(num);       
        Console.ReadLine();
}
public static void Example(int n)
{
            n = 100;
            }
}


Output

10000

The value passes the value type variable num in the preceding Example. As a result, changes to the Example () method do not affect num, whereas the reference type variable myStr is sent by reference to the ProcessString() method. As a result, any modifications to the ProcessString() method will be reflected. Value type variables must occasionally be passed by reference. So, how do you go about it?

The keywords ref and out in C# allow us to transmit value type variables to another function using references.

The ref keyword is used to transmit a value type variable by reference in the following Example.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example: Passing Value Type Variable With Reference

using System;

public class Program
{
public static void Main()
{
int num = 10;
        Example(ref num); //use ref to pass the parameter by reference 
           
        Console.WriteLine(num);
        Console.ReadLine();
}

public static void Example(ref int n)
    {
        n = 100;
    }   
}


Output:

100

As you can see in the preceding Example, the ProcessNumber() function uses the ref keyword to specify an int parameter. Thus we must use the ref keyword when sending this parameter to ProcessNumber(). It must be given a value before using the ref keyword to supply a variable as an argument. When passing to the method, we must include the ref keyword. Otherwise, a compile-time error will occur.

static void Main(string[] args)
{
    int num = 10;
    ProcessNumber(num); //Compile-time Error: Must use ref keyword 
           
    Console.WriteLine(num);
    Console.ReadLine();
}
 
public static void ProcessNumber(ref int n)
{
    n = n + 100;
}


The method can include other parameters with the ref parameter, as shown below.

static void Main(string[] args)
{
    int num = 10, val=0;
    ProcessNumber(ref num, val); 
           
    Console.WriteLine(num);
    Console.ReadLine();
}
 
public static void ProcessNumber(ref int n, int val )
{
    n = n + val;
}

Frequently Asked Questions

In C#, what is the purpose of the ref and out keywords?

The ref keyword indicates that the argument given to the method may be changed. The keyword is used to indicate that the parameter provided to the method cannot be changed. out is used to indicate that the method must modify the parameter given.

Why do we use the term "reference"?

In C#, the ref keyword is used to send and return references to and from Methods. Any change made to a value supplied by reference will be reflected because you are changing the deal at the address rather than the value itself.

Is C# ref faster?

No, it does not greatly enhance speed or anything else. On the contrary, employing the ref keyword adds another degree of indirection to the code, which can only slow it down. In most cases, parameters are passed by value, which means they are copied.

Conclusion

Let us brief out the article.

In this article, we study the ref keyword, its use cases, and different Examples for better understanding. That's all from the article.

I hope you all like this article. Want to learn more about Data Analysis? Here is an excellent course that can guide you in learning. You can also refer to our Machine Learning course.

Happy Learning, Ninjas!

Topics covered
1.
Introduction
2.
Example: Passing Value Type Variable
3.
Example: Passing Value Type Variable With Reference
4.
Frequently Asked Questions
4.1.
In C#, what is the purpose of the ref and out keywords?
4.2.
Why do we use the term "reference"?
4.3.
Is C# ref faster?
5.
Conclusion