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?
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.
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.
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.
In C#, ref
works for:
ref
doesn't work for:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With