Examples of using generic extension method

The following example shows how to use extension methods.

namespace GenericExtensions
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int>();
            intList.Add(1);
            intList.Add(2);
            intList.Add(3);
           
            List<int> newIntList = new List<int>();
            newIntList.Add(4);
            newIntList.Add(5);
           
            intList.Addlist(newIntList);

            foreach (int myInt in intList)
            {
                Console.WriteLine(myInt); // Should be 1,2,3,4,5
            }
          
            Console.ReadLine();
        }


    public static class Extensions
    {
        public static ICollection<T> Addlist<T>(this ICollection<T> src, ICollection<T> addingElements)
        {
            foreach (T element in addingElements)
            {
                src.Add(element);
            }
            return src;
        }
     
    }

    }


To understand the example above, Let's consider the figure below  if your extension method declares more than one parameter, only the first supports the this modifier, and the rest has to be specified as part of the method call as normal:

public static void Do_Stuff(this string value, string extra)
{                                            ^              ^
    ...                                      |              |
}                                            |              |
                                             |              |
+--------------------------------------------+              |
|                                                           |
|                                                           |
A_String.Do_Stuff("extra goes here");                          |
                        |                                   |
                        |                                   |
                        +-----------------------------------+
 
(This figure based on a post on stackoverfolow) 
The are some comments on the Do_Stuff method above.
- The type of the value parameter is the same as A_String's(particularly here is string)
- the method  must be declared as static

Conclusion:
If you want a object type (string, int, object...) add methods to existing types without creating new derived type
 or modifing the original type. Extension methods should be used in your case.
 
Share on Google Plus

About Chien

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment