Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

I'm trying to use the this keyword in a static method, but the compiler won't allow me to use it.

Why not?

like image 402
user18931 Avatar asked Sep 25 '08 16:09

user18931


People also ask

Why can't we use this keyword in static method?

No, we can't use “this” keyword inside a static method. “this” refers to current instance of the class. But if we define a method as static , class instance will not have access to it, only CLR executes that block of code. Hence we can't use “this” keyword inside static method.

Can we use this keyword in static method c#?

In C#, it is not allowed to use this to reference static methods or property accessors. In C#, if static keyword is used with the class, then the static class always contain static members.

Why can't we use this and super in static method?

Where the "super" keyword in Java is used as a reference to the object of the superclass. This implies that to use "super" the method should be invoked by an object, which static methods are not. Therefore, you cannot use the "super" keyword from a static method.

Can we use this in static class in C#?

In C#, one is allowed to create a static class, by using static keyword. A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class.


1 Answers

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.

like image 100
Kilhoffer Avatar answered Sep 18 '22 11:09

Kilhoffer