C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Ref returns and localsC# ref keyword allows a method to return reference rather than a value. In C# prior versions, a method can return only value. A variable that holds returned reference known as ref local. A method that returns reference has certain restrictions that are listed below.
Let's see an example. C# Ref Returns Example
using System;
namespace CSharpFeatures
{
class RefReturnsExample
{
public static void Main(string[] args)
{
string[] students = { "Rahul", "John", "Mayank", "Irfan" };
// Calling a method that returns a reference
ref string student = ref FindStudent(students, "John");
Console.WriteLine(student);
}
// A method that returns a ref type
static ref string FindStudent(string[] students, string student)
{
for (int i = 0; i < students.Length; i++)
{
if (students[i].Equals(student))
{
return ref students[i];
}
}
throw new Exception("Student not found");
}
}
}
Output: John Ref local is a variable that is used to store the reference returned by the method. Let's see an example. C# Ref Local Example
using System;
namespace CSharpFeatures
{
class RefReturnsExample
{
public static void Main(string[] args)
{
string[] students = { "Rahul", "John", "Mayank", "Irfan"};
Console.WriteLine("Array: [" + string.Join(",",students)+"]");
// Creating local reference
ref string student = ref students[3];
student = "Peter"; // It will change array value at third index
Console.WriteLine("Updated array: ["+string.Join(",",students)+"]");
}
}
}
Output: Array: [Rahul,John,Mayank,Irfan] Updated array: [Rahul,John,Mayank,Peter] |