Why can't you use the keyword 'this' in a static method in .Net?

That's an easy one. The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class. There is a much more in depth explanation of what static members are and why/when to use them in the MSDN docs.


As an additional note, from a Static method, you can access or static members of that class. Making the example below valid and at times quite useful.

public static void StaticMethod(Object o)
{
     MyClass.StaticProperty = o;
}

Static methods are Class specific and not instance specific. "this" represents an instance of the class at runtime, so this can't be used in a static context because it won't be referencing any instance. Instead the class's name should be used and you would only be able to access static members in the class

Tags:

C#

.Net