Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't returning by ref work for elements of collections?

Tags:

The following example of returning by reference is from What’s New in C# 7.0:

public ref int Find(int number, int[] numbers) {     for (int i = 0; i < numbers.Length; i++)     {         if (numbers[i] == number)         {             return ref numbers[i]; // return the storage location, not the value         }     }     throw new IndexOutOfRangeException($"{nameof(number)} not found"); } 

That compiles without any problems (as you'd expect as it's copied from the Microsoft blog).

I've written this one:

private static ref int GetReference(string searchTerm) {     var passwords = new Dictionary<string, int>     {         {"password", 1},         {"123456", 2},         {"12345678", 3},         {"1234", 4},         {"qwerty", 5},         {"12345", 6},         {"dragon", 7}     };      return ref passwords[searchTerm]; } 

This one doesn't compile though; it gives the following error:

CS8156 An expression cannot be used in this context because it may not be returned by reference

Why does returning from an array work, but returning from a collection doesn't?

like image 347
BanksySan Avatar asked Apr 23 '17 21:04

BanksySan


People also ask

How does ref work in c#?

The ref keyword in C# is used for passing or returning references of values to or from Methods. Basically, it means that any change made to a value that is passed by reference will reflect this change since you are modifying the value at the address and not just the value.

What is ref and out parameter in C#?

ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.

Are lists passed by reference in C#?

Your List is an object created on heap. The variable myList is a reference to that object. In C# you never pass objects, you pass their references by value.


1 Answers

In C#, ref works for:

  • Variables (local or parameters)
  • Fields
  • Array locations

ref doesn't work for:

  • Properties
  • Events
  • Local variables in the case of C# 7 return by ref

Note that for fields and array locations, it doesn't matter how you're accessing the array. That is, return ref numbers[i]; doesn't hold on to numbers, but to the array it points to. Quite unlike return ref numbers;, which could only work if numbers was a field.

However, you're using ref on a Dictionary<,>'s index property, it's simply not a supported expression for ref to begin with (i.e. you can't pass ref passwords[searchTerm] as an argument even before C# 7), much less to return by ref.

like image 54
acelent Avatar answered Sep 26 '22 00:09

acelent