2

Lets say we have the following function:

public static void AddTo(this int inInt, int inAmountToAdd)
{
    inInt += inAmountToAdd;
}

This will simply modify the parameter value "inInt".

Can I somehow get a reference to the value type object calling this static extension method in order to modify it?

Harald Kanin
  • 133
  • 5

1 Answers1

4

In C# 7.2, ref extension methods are allowed. This was not allowed in prior versions. You would have to declare the method like this:

public static void AddTo(this ref int inInt, int inAmountToAdd)
{
    inInt += inAmountToAdd;
}

And then also use VS 2017 (requires version 15.5 or newer) with the language version set to 7.2 (or latest).

Note that when you use this feature, the caller must call the method with something that can act as ref in the receiver position (i.e. a field, local variable, or array slot). If you were planning on using this in some kind fluent API, it might not work as expected. For example, this would fail to compile: GetInt().AddTo(1) because the return value of the method GetInt is not a valid ref.

Note the above syntax might require 15.6 as per this issue but the feature should be available in 15.5 using ref this if I am reading this correctly.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
  • Do you have a link to where I can read up on this? I searched but wasn't able to find it in the "What is new in C# 7.2". I found a bunch of feature requests, but not anywhere showing that it was completed and included. – Cory Apr 17 '18 at 03:23
  • 1
    @Cory The [c# language repo](https://github.com/dotnet/csharplang) is good place to look. I found this [item](https://github.com/dotnet/csharplang/blob/38370edf77e23da6c459bfbdf7c36dacd14eea7f/proposals/csharp-7.2/readonly-ref.md) which made me think it was not fully implemented, but i tried it on [sharplab.io](https://sharplab.io/) which allows you to run very recent (nightly?) compiler builds and it worked. So I tried it in a somewhat up to date VS 2017 and it provided helpful error messages about enabling 7.2. – Mike Zboray Apr 17 '18 at 03:32