16

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?

airbai
  • 3,906
  • 5
  • 26
  • 30
  • Static Classes and Static Class Members (C# Programming Guide): http://msdn.microsoft.com/en-us/library/79b3xss3.aspx – Hans Olsson Aug 11 '10 at 14:24
  • 2
    Can you tell us what you want to do, and why you think it would involve the combination of `static` and `this`? Usually if you need to mix the two, you call a static method from a non-static method (or reference a field, set a property, etc.) – We Are All Monica Aug 11 '10 at 14:30
  • 1
    I always wanted to have a keyword in static methods which says current class. This can avoid lots of mistakes and copy&paste errors if you need the type of the current class. But I wouldn't name it this but class :) – codymanix Aug 11 '10 at 15:13
  • I can't help but wonder if this question was nothing more than a new user trying to get their rep up so that they can actually do rep-restricted actions on this site. Don't suppose I can say much though, because I did the exact same thing! :D – Jagd Aug 11 '10 at 17:03
  • Important to note that this isn't a constraint, is part of the definition of what a static method/property is: something common to all instances, so it can't have the reference to any specific instance. Also as someone pointed out in other comment, it isn't specific to C#: Java and nearly all object-oriented languages have the concept. – Monoman Aug 11 '10 at 17:16
  • I'm giving you -1 for asking this question here. This is something you should be covered in a basic programming guide. I'm agreeing with Jagd here. – codemonkeh Aug 12 '10 at 01:10
  • Sorry - I felt compelled by some demonic force to vote this down. It really annoys me that some people have no clue what a class method is and clearly have not tried to research it, but instead assume that Static means the same as it did in VB6. I'll get over it though... – CompanyDroneFromSector7G Oct 08 '14 at 12:08

13 Answers13

60

Because this points to an instance of the class, in the static method you don't have an instance.

The this keyword refers to the current instance of the class. Static member functions do not have a this pointer

You'll notice the definition of a static member is

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object

Which is why this has nothing to point to.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • 2
    Please explain why there's no instance in a static method :) – Blixt Aug 11 '10 at 14:22
  • 4
    Think 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. – Blub Aug 11 '10 at 14:30
  • 21
    I can't imagine a static animal, not to mention one that eats. – jessegavin Aug 11 '10 at 15:10
14

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.

AMAN SINGH
  • 3,491
  • 6
  • 28
  • 44
Shawn D.
  • 7,895
  • 8
  • 35
  • 47
2

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.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
2

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.

madcapnmckay
  • 15,782
  • 6
  • 61
  • 78
2

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.

Lazarus
  • 41,906
  • 4
  • 43
  • 54
  • For 'this isn't limited to C# and it isn't a constraint, it's a logical situation', I agree : ) – airbai Aug 12 '10 at 01:09
2

By static methods you can write:

MyClass.static_method();

which there is nothing to do with any object instance (so you don't need this keyword).

Because static_method() works and doesn't need object instances for its job. static_method() doesn't know which object instance do you have, but it can change the behavior of all object instances:

MyClass a = new MyClass();
MyClass b = new MyClass();
MyClass.static_method("PRINTER");
a.display(); //print something
b.display(); //print something
MyClass.static_method("MONITOR");
a.display(); //display something on monitor
b.display(); //display something on monitor

In this case, static_method() changes the behavior of display() method in all object instances of MyClass.

Sadeq
  • 7,795
  • 4
  • 34
  • 45
1

The keyword this refers to the instance of the object. In the static context there is not specific instance to reference.

Jerod Houghtelling
  • 4,783
  • 1
  • 22
  • 30
1

The this keyword can be used in a method marked as static. The syntax is used to define extension methods in C#. This feature has been available since C# 3.0, released in 2007 (Wikipedia)

In the normal usage, this refers to the instance, static says that there is no instance (and therefore no this). The fact that you can't use them together (aside from special exceptions like extension methods) follows naturally from understanding what this and static are, conceptually.

pjpants3k
  • 41
  • 4
0

this is used to refer to the parent object of a variable or method. When you declare static on a method the method can be called without needing to instantiate an object of the class. Therefore the this keyword is not allowed because your static method is not associated with any objects.

Covar
  • 901
  • 1
  • 7
  • 15
0

'this' refers to an instance of a class. Static is initialized without instantiation and hence the static method cannot refer to an 'instance' that is not created.

happyfeet
  • 133
  • 1
  • 2
  • 8
0

The short answer for you will be: this refers to an instance of a class which is non existing in a static scope.

But please, look for a good book/class and try to understand basic object oriented concepts before going further on any object oriented programming language.

Miguel
  • 1,575
  • 1
  • 27
  • 31
0

I am not sure if this helps your problem, but I believe these two code snippets are equivalent:

MyStaticClass.foo();

and simply

foo();

will both call the foo() method in the MyStaticClass class, assuming you call foo() from inside MyStaticClass

Edit - The easiest way to remember the difference between a static class and a non-static class is to think of something like the Math class in java. You can call Math.abs(x); to get the absolute value of x, and it does not really make sense to instantiate a Math object, which is why Math is a static class.

jbabey
  • 45,965
  • 12
  • 71
  • 94
0

Another, more literal, take on your question:

The 'this' keyword can't be used in a static method to avoid confusion with its usage in instance methods where it is the symbol to access the pointer (reference) to the instance passed automatically as a hidden parameter to the method.

If not by that you could possibly define a local variable called 'this' in your static method, but that would be unrelated to the 'this' keyword referenced instance in the instance methods.

Below is an example with two equivalent methods, one static the other an instance method. Both method calls will pass a single parameter to the methods executing code that will do the same thing (print the object's string representation on the console) and return.

public class Someclass {

  void SomeInstanceMethod() 
    { System.Console.WriteLine(this.ToString()); }

  void static SomeStaticMethod(Someclass _this) 
    { System.Console.WriteLine(_this.ToString()); }

  public void static Main()
    {
       Someclass instance = new Someclass();
       instance.SomeInstanceMethod();
       SomeStaticMethod(instance);
    }
}
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Monoman
  • 721
  • 10
  • 12