I just read about Extension methods so thought to write about it so as to give brief idea about this feature introduced in C# 3.0.
Extension Methods:static methods that you can invoke using the instance method syntax.
Introduction 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.
behavior is similar to that of static methods. You can declare them
only in static classes. To declare an extension method, you specify the
keyword this as the first parameter of the method, for example:
public static class Abc
static void extPrint(this
static void staticPrint(string s)
static void Main(string args)
"A".extPrint(); --------- Print A
staticPrint("Hello"); --------- Print Hello
As you can see from the above snippet, the differences between the extension method extPrint() and the regular static method (staticPrint) are the following:
- Extension methods have the keyword this before the first argument. Static methods do not have the this keyword in its argument declaration.
- When extension methods are consumed, the argument that was declared with the keyword this is not passed. In the above code, A is an example of consuming the extension method extPrint.
No argument is passed to it. When static methods are consumed, no
arguments are skipped. All expected arguments must be entered. Hello is an example of this.
- Extension methods can be defined only in a static class. For static
methods, this is not a requirement. Static methods can exist in a
regular class as well as in a static class.
- Extension methods can be called only on instances values.