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?
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.
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.
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.
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.
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)
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