Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of "this" keyword in formal parameters for static methods in C#

I've come across several instances of C# code like the following:

public static int Foo(this MyClass arg) 

I haven't been able to find an explanation of what the this keyword means in this case. Any insights?

like image 854
kpozin Avatar asked May 11 '09 05:05

kpozin


People also ask

Can 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 you use this keyword in static class?

Output. The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.

Why this keyword is not used in static method in C#?

No, we can not used "this" keyword within a static method. because "this" keyword refers to the current instance of the class. Static Member functions do not have a this pointer (current instance). Note - we can also not used "base" keyword within a static method.

How do I use this keyword as a parameter?

To pass the object of the same class as a parameter to a method, the syntax will be: method_name(this); In the above syntax, 'this' keyword refers to the object of the current class and method_name is the name of the method to be called.


1 Answers

This is an extension method. See here for an explanation.

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework... .

it means that you can call

MyClass myClass = new MyClass(); int i = myClass.Foo(); 

rather than

MyClass myClass = new MyClass(); int i = Foo(myClass); 

This allows the construction of fluent interfaces as stated below.

like image 87
Preet Sangha Avatar answered Sep 27 '22 22:09

Preet Sangha