SIGN UP MEMBER LOGIN:    
ARTICLE

Extension Methods in C#

Posted by Moustafa Arafa Articles | Learn .NET March 17, 2009
In this article I would like to introduce one of new C# 3.0 enhancements “Extension Methods” and so on.
Reader Level:
 

Introduction

In this article I would like to introduce one of new C# 3.0 enhancements "Extension Methods" and so on. This feature is available in C # 3.0 compilers and further versions (C# 4.0); this feature is very important for all developers especially if you would like to use the dynamism of the C# enhancements to be taken place in your classes design.

  1. Why do we need Extension Methods?

    While designing your classes in .NET projects, we used to have siblings classes which do simple operation from its parent classes to add a kind of customization for parents' methods. Suppose that you want to extend int class in .NET by adding a factorial method to it using recursion technique.

    One way of thinking is to inherent int class and adds your new method on it and use your new methods in your code, this is a valid solution but let us see what extension methods can provide us.

    Using extension methods you can use your new methods as a part of int class in .Net



    In the above screen shot, I wrote the following line of code:

    int x = 3;
    x.factorial();

    Factorial method becomes a part of int class by implementing factorial method as an extension method in my class without inheriting int class in .NET.
     
  2. What's the specification of an extension method?

    An extension method is a special kind of static method that allows you to add new methods to existing types without creating derived types.

    The extension methods are called as if they were instance methods from the extended type, For example: x is an object from int class and we called it as an instance method in int class.
     
  3. How to create my extension method?

    Simply, you create your own static method in your class and put this keyword in front the first parameter in this method (the type that will be extended).
    public static class MyMathExtension
        {
            public static int factorial(this int x)
            {
                if (x <= 1) return 1;
                if (x == 2) return 2;
                else
                    return x * factorial(x - 1);
            }
        }
     
  4. Complete code for my demo :

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int x = 3;
                Console.WriteLine(x.factorial());
                Console.ReadLine();
            }
        }

        public static class MyMathExtension
        {
            public static int factorial(this int x)
            {
                if (x <= 1) return 1;
                if (x == 2) return 2;
                else
                    return x * factorial(x - 1);
            }
        }
    }

  5. General Tips in extension methods usage:

    This section is optional reading section for understanding the core idea of extension methods:

    • This keyword has to be the first parameter in the extension method parameter list.
    • Extension methods are used extensively in C# 3.0 and further version specially for LINQ extensions in C#, for example:
      int[] ints = { 10, 45, 15, 39, 21, 26 };
      var result = ints.OrderBy(g => g);
      Here, order by is a sample for an extension method from an instance of IEnumerable<T> object, the expression inside the parenthesis is a lambda expression.
    • It is important to note that extension methods can't access the private methods in the extended type.
    • If you want to add new methods to a type you don't have the source code for it, the ideal solution is to use and implement extension methods of that type.
    • If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called.

Conclusion

In this article, I have stated the use and the benefits we will gain by using extension methods in C# which is available starting from C# 3.0 and further versions of C#.

It's important to take care of the tips I have mentioned in the article while you implementing your extension methods.

Login to add your contents and source code to this article
share this article :
post comment
 

ASP.net Ajax Control Toolkit Color Picker Extender have a SampleControlID property, that shows the selected color's hexadecimal color code value for further use. But some time for better ui visibility need, if you don't want that hexadecimal color code to appear in the same control, then here is the way to do that.

In this sample code below:
I used a TextBox (txtColor) as ColorPickerExtender's SampleControlID and TargetControlID.
I used a ImageButton(ibtnCollorPicker) with ColorPickerExtender's PopupButtonID.
 
Now, when I click on the ibtnCollorPicker, this will show the colorpicker. Any color selection done, will show the hexa value in the txtColor.
Method 1:  (Mostly Used By Developers)

On color selection, the selected color of color picker becomes the both the fore color and background color of the textbox. So since the hexa value does not appear directly.

<asp:TextBox ID="txtColor" runat="server"></asp:TextBox>
<asp:ImageButton ID="ibtnCollorPicker" runat="server" ImageUrl="~/Images/color_button.png"
        ToolTip="Pick Color"></asp:ImageButton>
 
<cc:ColorPickerExtender ID="txtColor_ColorPickerExtender" runat="server" 
                        TargetControlID="txtColor" SampleControlID="txtColor" 
                        OnClientColorSelectionChanged="changeColor"
                        PopupButtonID="ibtnCollorPicker">
</cc:ColorPickerExtender>
 

function changeColor(sender)
        {
            sender.get_element().style.color = sender.get_selectedColor();           
 
        }
 
It works fine but it has a small issue. After selection, if you highlight textbox text with the help of mouse, then the hexa value will appear again.
Method 2 contains solution of this.

Posted by eliza sahoo Jun 07, 2010

thanks so much eng.Moustafa Arafa i'm junior developer and I really appreciate your effort really I found this article useful eng.Mohammed Gaber

Posted by mohammed gaber Mar 28, 2009
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor