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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With