What is Extension method?

An extension method is a static method of a static class that can be invoked like as an instance method syntax. Extension methods are used to add new behaviors to an existing type without altering.
In extension method “this” keyword is used with the first parameter and the first parameter will be of type that is extended by extension method. Other parameters of extensions types can be of any types (data type).
Example:

//defining extension method
public static class MyExtensions {
	public static int WordCount(this String str) {
		return str.Split(new char[] {
			' ', '.', ','
		}).Length;
	}
}
class Program {
	public static void Main() {
		string s = "Dot Net Tricks Extension Method Example";
		//calling extension method
		int i = s.WordCount();
		Console.WriteLine(i);
	}
}
//output: 6

Key points about extension method

  1. An extension method is defined as static method but it is called like as an instance method.
  2. An extension method first parameter specifies the type of the extended object, and it is preceded by the “this” keyword.
  3. An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
  4. An extension method couldn’t override the existing instance methods.
  5. An extension method cannot be used with fields, properties or events.
  6. The compiler doesn’t cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.
Tagged , . Bookmark the permalink.

Leave a Reply