Search code examples
c#extension-methodsrefc#-7.2

What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension methods?


Consider the following extension methods:

public static void Toggle(this ref bool @bool) => @bool = !@bool;

public static void Toggle2(ref this bool @bool) => @bool = !@bool;

These simply toggle a ref boolean variable value. Testing:

class Foo
{
    private bool _flag;
    public void DoWork()
    {
        _flag.Toggle();
        Console.WriteLine(_flag);
        _flag.Toggle2();
        Console.WriteLine(_flag);
    }
}

We get:

True
False

The question: Is there any hidden difference in choosing one syntax or the other?


Solution

  • There is no difference. These are called modifiers, and their order in the specification is not defined.

    You can read the section on method parameters in C# Language Specification here:

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#method-parameters

    It lists out the different options and defines how they interact and mix, but says nothing about what order you must use.