I\'m trying to use the this
keyword in a static method, but the compiler won\'t allow me to use it.
Why not?
For OP's question, refer to the accepted answer. This answer is for the ones who're looking for a fast one liner to use in static methods.
If the class is a form, and it's open (you need the name of the form as well), this can be called within a static method;
Application.OpenForms["MainForm"];
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;
}
If You want to use non static function of class in static function.Create object of class in static function. For Eg
Class ClsProgram(){
public static void staticfunc(){
ClsProgram Obj = new ClsPrograM()
Obj.NonStaticFunc();
}
public void NonStaticFunc(){}
}
this represents the current instance object and there is no instance with static methods.
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