Extension Methods in C#


The .NET framework comes with a set of inbuilt classes and types which we use extensively in our applications. Integer, string, float etc are some of these which are very frequently used. These come with a set of predefined methods and properties. Lets say we declare a string variable in our program, we can use a list of methods that are provided by the .NET framework within it.

ExtMethd1.gif

Suppose we have to execute a custom method on any string object for a number of times in our code. Wouldn't it be great if we could just execute it as any_string_object.ourCustomMethod().

Extension methods help us achieve
 exactly this. Without using Inheritance, we can extend the existing classes to add our own methods.

Lets say we have a integer and we need to check : if the interger is <100, the integer is divisible by 2. We'll write an extension method for this.

The extension method is written inside a static class and the method is also defined as static. Though it is defined as a static method it is still invoked on a particular instance. Below is the code for the extension method isAllowed()

ExtMethd2.gif

The "this" keyword tells that the method should be associated with the type specified ahead of it. In this case it is INT
Here the extension method is invoked on the variable that we have read through the console. We can use this method on any other integer variable in the program.

ExtMethd3.gif

The result of the program is :

ExtMethd4.gif

Extension methods cannot be used to override existing methods and these can be applied only to add extension methods. We cannot create properties using the above concept.

Up Next
    Ebook Download
    View all
    Learn
    View all