Extension Method in c# .net with example

Extension methods in C# allows to add method to a class in library (.dll) being used making no change to that library. Extension methods are limited to the instance and if the same class of the library being used in another project, the effect will not reach there until extension method is added there as well because the extension method is limited to the project.

substring in JavaScript gets start and end indexes to extract string from another string e.g. abcdefghi.substring(3,4) will return d. We will create the equivalent in c# through creating extension method.

You can write your own extension method this way:

public static partial class FirstExtension
{
	public static string substringJS(this string s,int start,int end)
	{
		return s.Substring(start, end - start + 1);
	}
}

usage:

string newstr = "abcdefghi".substringJS(start,end);

How extension method work

Class FirstExtension is not adding to extension method rather we are just defining extension method in this class. Extension method code can be added to any static class.

The first parameter of the extension method is the instance of the class where the extension method is being added, this string s in above example.

The class must be static where the extension method code being defined.

Posted Status in Programming
Login InOR Register