What does "this" mean in a static method declaration?

I saw code that uses the this in a function parameter declaration. For instance:

 public static Object SomeMethod( this Object blah, bool blahblah) 

What does this mean in this context?

+6
syntax methods c # extension-methods
source share
3 answers

This means that SomeMethod() is an extension method to the Object class.

After defining this method, you can call this method on any instance of Object (despite being declared static ), for example:

 object o = new Object(); bool someBool = true; // Some other code... object p = o.SomeMethod(someBool); 

The this Object parameter refers to the object that you are calling it, and is not actually found in the parameter list.

The reason she declared static when you call it as an instance method is because the compiler translates this into a real static call in IL. This goes deep down, so I will not dwell on it in detail, but it also means that you can call it as if it were some static method:

 object o = new Object(); bool someBool = true; // ... object p = ObjectExtensions.SomeMethod(o, someBool); 
+13
source share

How do you declare an extension method .

This means that you can call SomeMethod with .SomeMethod for any object. Object in front of . it is blah parameter.

 string s = "sdfsd"; Object result = s.SomeMethod(false); 

The extension method will be available for all types that inherit from the type of the this parameter, in this case the object. If you have SomeMethod(this IEnumerable<T> enumerable) , it will be available to all IEnumerable<T> : s like List<T> .

+2
source share
+1
source share

All Articles