In C# 7.0, lots of enhancements and new features have been introduced with Visual Studio 2017 which makes developers' lives easy. Let's explore two of these features, like ref return and out variable, with a small example which will help us to understand easily.
This is part three of C# 7.0, If you want to read about more feature then visit the below links for other parts,
This is part three of C# 7.0, If you want to read about more feature then visit the below links for other parts,
Ref Returns
In C#7, the Ref keyword allows code to pass a value type variable by reference as a parameter of a method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword. Here, I have chosen FindFruits() to demonstrate the ref returns feature. FindFruits() method has a two parameter index, a list of fruits and it has a ref string return type, this method returns fruit names based on the passed index.
In C#7, the Ref keyword allows code to pass a value type variable by reference as a parameter of a method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword. Here, I have chosen FindFruits() to demonstrate the ref returns feature. FindFruits() method has a two parameter index, a list of fruits and it has a ref string return type, this method returns fruit names based on the passed index.
Initially, I have passed position = 2, so this method will return output as "Papaya" from the list then I assigned "Watermelon" to secondFruit ref variable. Now, if I try to pass the same position in this list then I will get newly replaced fruit from the list.
Ref keyword that can be used to return values by a ref. Line 17 created a method with return type ref string, Ref can also be used for storing values by a ref in the local variable. Line 12 stored values in secondFruit ref variable,
- class Program
- {
- static void Main(string[] args)
- {
- string[] listOfFruits = { "Mango", "Banana", "Papaiya", "Chiku", "MuskMelon"};
- int position = 2;
- ref string secondFruit = ref FindFruits(position, listOfFruits);
- Console.WriteLine($"Fruit Number Two : {secondFruit}");
- secondFruit = "Watermelon";
- Console.WriteLine($"Second fruits is replaced with {listOfFruits[position]}");
- Console.ReadLine();
- ref string FindFruits(int index, string[] fruitList)
- {
- if (fruitList.Length > 0)
- return ref fruitList[index]; // this return the location not the value
- throw new IndexOutOfRangeException($"{nameof(index)} not found");
- }
- }
- }


Murali KrishnanPosted Sep 5, 2018, 1:51 AM
Thanks Jignesh :) on behalf of MC05
Mahesh ChandPosted Jul 30, 2018, 9:39 AM
Now, you can add "in" modifier as well. It's ref, out, and in now in C# 7.2.