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

Epicor 9 ToolBars

Like any other application, Epicor has list of toolbars and it uses the Infragistics controls and you can modify these toolbars in your code by adding new tools or change the properties for the existing toolbars and Tools.

How to Set the Default Value for Fields in Epicor Customization

Let suppose you want to set the default value for PurAgent.EMailAddress field in the Buyer Maintenance Form. You have first to open the Buyer Maintenance Form in customization mode (using Developer mode).