Skip to main content

Extension Methods in c#

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

The extension methods must:
·         Must be Public.
·         Accept at least one parameter; the type of this parameter defines the class that you are extending.
·         Exist within a static class.
·         Be A static method.
·         Include this keyword in the parameter.
The following example shows extension methods defined for the int class.

namespace ExtentionMethods
{
    public static class Extenions
    {
        public static bool IsOdd(this int value)
        {
            return (value % 2 != 0);
        }

       public static bool IsEven(this int value)
        {
            return (!IsOdd(value));
        }

    }

}

The IsOdd & IsEven extensions methods can be brought into scope with this using directive:
Using ExtentionMethods;
int number = 10;
bool odd=number.IsOdd();
bool even= number.IsEven();
 
You will notice the “extension” word in the visual studio intelliSense as below:
 

 
And you can use it as below:
 
int number = 10;
Extenions.IsOdd(number);


If you forget to include this keyword in the parameter of the extension method so you can’t call it as below because the method is not extended the int type.

int number = 10;
bool odd=number.IsOdd();
 
But you can call it using the class name and the method name as below:

int number = 10;
Extenions.IsOdd(number);


Important Notes:

-    If you created an extension method with the same signature of built-in method so the built-in method always takes precedence over the extension method.
-    There are many extension methods added by Microsoft any all types and you can use it.

I hope this will help you to improve your skills in Programming

Comments

Popular posts from this blog

Automatic Login to Epicor

Overview: When the user double-clicks on the program icon in the desktop, Epicor Login window will appear and ask the user to enter the user name and password. But you can modify the configuration setting file so the user can automatically login into the application.

How to use Process Sets Maintenance

The process sets program uses to group a list of task together to be run in a schedule and you can order the task to be run in your order especially if you have a task depend another task.