Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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
thiskeyword was found outside of an instance method, instance property, constructor, or indexer (for example, in a field initializer or a static method). - The
thisparameter modifier was used on a method declaration inside anextensiondeclaration block. In anextensiondeclaration, extension members are declared as instance members without thethismodifier 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; }
}
}
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.