The ref keyword in C# 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.
- class Program
- {
-
- static void Main(string[] args)
- {
- long total = 0;
- AuthorByRefParam(5, 10, ref total);
- Console.WriteLine(total);
- Console.ReadKey();
- }
-
- static void AuthorByRefParam(long a, long b, ref long total)
- {
- total = a + b;
- }
-
- }
Listing 1
The code snippet in Listing 1, AuthorByRefParam, accepts the third parameter by reference. The caller program calls the method by initializing a variable and passes it as a parameter by explicitly using the ref keyword.
In C# 7.0, value can be returned and stored locally by ref.
C# 7.0 introduced an improved ref keyword that can be used to return values by ref. Ref can also be used for storing values by ref in the local variable. You may want to read the article, Concepts of C#: Value type vs Reference type, if you’re not familiar with these concepts.
The code snippet in Listing 2 lists a method, FindAuthor, that returns a string value by reference.
- class Program
- {
-
- static void Main(string[] args)
- {
-
-
- string[] authors = { "Mahesh Chand", "Mike Gold", "Dave McCarter", "Allen O'neill", "Raj Kumar" };
-
-
- ref string author4 = ref new Program().FindAuthor(3, authors);
- Console.WriteLine("Original author:{0}", author4);
-
-
- Console.WriteLine();
-
-
- author4 = "Chris Sells";
-
-
- Console.WriteLine("Replaced author:{0}", authors[3]);
-
-
- Console.ReadKey();
-
- }
-
- public ref string FindAuthor(int number, string[] names)
- {
-
- if (names.Length > 0)
- return ref names[number];
- throw new IndexOutOfRangeException($"{nameof(number)} not found.");
-
- }
Listing 2
Summary
Ref returns is a new concept introduced in C# 7.0. In this article, we learned how to use this feature.
References
References used to write this article:
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/