Extension Methods

Extension methods in C# is a great way to add functionality to a closed class. Here the word ‘closed’ refers to both the sealed ones and the classes which you do not have the access to their source code.

Some can argue if we can actually add a method to a sealed class then it violates the sealed concept. In way it is but not indeed.

There are plenty few points you have to be aware of whilst implementing an extension method for a class in C#

■ Extension methods must be defined in a  C# public static class.
■ If you define an extension method for a type, and the type already has the same
method, the type’s method is used and the extension method is ignored.
■ Although extension methods are implemented as static methods,
they are instance methods on the type you are extending. You cannot add static methods
to a type with extension methods.

The last point is bit confusing, how come a method marked as static work as a non static method. This is a special case in C# where one of the basic rules is violated.

So let’s see how you can create an extension method for String type.

public static class StringHelper { public static bool IsNumeric(this string num, out double result) { return Double.TryParse(num, out result); } }

Create a helper class like the above one. But note how the IsNumeric is declared and it’s parameters. In an extension method the first parameter should be always the type on which the extension method is targeted on. And should have the ‘this’ keyword before. Other parameters are custom defined.

Just that it’s simple

double value; string myString = "Thuru"; myString.IsNumeric(out value);

You can call the extension method as it is declared in the String. This is really cool.

And also if you consider the last point of the extension method now you can understand why the static – instance violation is made. Because if the extension method is static then all the string values declared in the scope of this IsNumeric would be effected.

So in the extension method declaration the static is a mere format keyword and makes sense because the methods are under a static class. Real sense of static is not considered. As like having an awkward syntax of having ‘this’ keyword in the parameter list.


Comments are closed.

Powered by WordPress.com.

Up ↑

%d bloggers like this: