Tuesday, February 8, 2011

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

I guess that's a real noobie question, but I'm new to OO and .Net. I just don't understand why it can't be done.

  • 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.

    From Kilhoffer
  • 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

    From
  • this represents the current instance object and there is no instance with static methods.

    From CSharpAtl
  • 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;
    }
    
  • there is no this there

0 comments:

Post a Comment