Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C#'s ref features on (dictionary) indexers

Tags:

c#

ref

I was wondering whether it is possible to use C#'s ref return on (dictionary) indexers or properties which define a set and get accessor, e.g.:

readonly Dictionary<string, int> dictionary = ...;


ref int v = ref dictionary["foo"];
//          ^^^^^^^^^^^^^^^^^^^^^
// CS0206: A property or indexer may not be passed as an out or ref parameter
v = 42;

Is it possible to somehow provide ref functionality to properties or indexers (without using reflection)? If so, how?


I know, that the error message is clear in that sense - however, I was wondering which would be the optimal way to implement its semantics.
like image 259
unknown6656 Avatar asked May 25 '18 10:05

unknown6656


People also ask

What is C in used for?

C is a programming language that is both versatile and popular, allowing it to be used in a vast array of applications and technologies. It can, for example, be used to write the code for operating systems, much more complex programs and everything in between.

Is C used nowadays?

There is at least one C compiler for almost every existent architecture. And nowadays, because of highly optimized binaries generated by modern compilers, it's not an easy task to improve on their output with hand written assembly.

Why do people use C?

As a middle-level language, C combines the features of both high-level and low-level languages. It can be used for low-level programming, such as scripting for drivers and kernels and it also supports functions of high-level programming languages, such as scripting for software applications etc.

Is C Programming good for beginners?

As I have said, C is a powerful, general-purpose programming language, and it's also a great language to learn when you start with programming. It gives you a lot more control over how your program uses memory, which is a tricky part but also very important if you want to become a better programmer.


1 Answers

This requires the type implementing the indexer to provider ref-return in the indexer, so no: you can't use it with Dictionary<string, int>. But with something like this:

class MyRefDictionary<TKey, TValue>
{
    public ref TValue this[TKey key]
    {   // not shown; an implementation that allows ref access
        get => throw new NotImplementedException();
    }
}

You could indeed do:

ref var val = ref dictionary[key];

Note that arrays are a special case, as arrays have always allowed ref indexer access, i.e.

SomeMethod(ref arr[42]);

(the indexer access in arrays is implemented by the compiler, not the type)

like image 150
Marc Gravell Avatar answered Sep 29 '22 08:09

Marc Gravell