Why keyword 'this' cannot be used in a static method?
Solution 1
Because this
points to an instance of the class, in the static method you don't have an instance.
You'll notice the definition of a static member is
Which is why this
has nothing to point to.
Solution 2
this
is an instance of the current object. With a static method, there is no current object, and as such, this
doesn't exist. It's not really a constraint, but the entire point of a method being static.
Solution 3
this
refers to the current instance of a class and can therefore be used only in instance methods. Static methods act on class level, where there are no instances. Hence, no this
.
Solution 4
this
refers to the current instance of the object. A static method is a method on the class. It is not an instance method and therefore using this inside a static method is meaningless.
Solution 5
I'm pretty sure this isn't limited to C# and it isn't a constraint, it's a logical situation. As @Yuriy correctly states, this refers to the current instance of a class, i.e. you've used new (or DI) to instantiate the class (created an instance of) and you need some way internally to refer to that instance, i.e. this object. A static method is called without instantiating the class, there is, in effect, no object created and as such you can't access properties of which this is one.
Comments
-
airbai over 3 years
Why can't the keyword
this
be used in a static method? I am wondering why C# defines this constraint. What benefits can be gained by this constraint?[Update]: Actually, this is a question I got in an interview. I do know the usage of 'static' and 'this', based on all your response, I guess I know a little of why the two can not be used together. That is, for static method is used to changed state or do something in a type level, but when you need to use 'this' means you want to change the state or do something in a instance level. In order to differentiate the state change of a type and the state change of an instance, then c# donot allow use 'this' in a static method. Am I right?
-
Muhammad Huzaifa almost 14 yearsPlease explain why there's no instance in a static method :)
-
Blub almost 14 yearsThink about how you call static methods. Class.Method() like Animal.Eat() You never needed an instance (new Animal()) for calling the static method. That's why there is none.
-
strager almost 14 yearsYou're mixing C++ and C# here, I think.
-
jessegavin almost 14 yearsI can't imagine a static animal, not to mention one that eats.
-
Monoman almost 14 yearsThanks jleedev for the formatting. Doesn't know how to do it, yet. :)
-
airbai almost 14 yearsFor 'this isn't limited to C# and it isn't a constraint, it's a logical situation', I agree : )