Edit

Compiler Error CS0027

Keyword 'this' is not available in the current context

The this keyword was used in a context where it is not valid. Common causes include:

  • The this keyword was found outside of an instance method, instance property, constructor, or indexer (for example, in a field initializer or a static method).
  • The this parameter modifier was used on a method declaration inside an extension declaration block. In an extension declaration, extension members are declared as instance members without the this modifier on their parameters because the receiver is specified in the extension header.

Examples

The following example generates CS0027 because this is used in a field initializer:

namespace ConsoleApplication3
{
    class MyClass
    {
        int err1 = this.Fun() + 1;  // CS0027: 'this' is not valid in a field initializer

        public int Fun() => 10;

        public void Test()
        {
            // Valid use of this
            int err = this.Fun() + 1;
            Console.WriteLine(err);
        }
    }
}

The following example generates CS0027 because an extension method with a this parameter modifier is declared inside an extension declaration block:

public static class Extensions
{
    extension(int q)
    {
        // CS0027: Cannot use 'this' parameter modifier inside an extension block
        public static void MethodWithThis(this int p) { }

        // Correct: Declare as an extension method using the receiver parameter 'q'
        public void ValidMethod() { int z = q; }
    }
}