What are Extension Methods and how to implement them



While working with system classes like int, double, string or any third party library, you may have wished that it would be nice to have some methods or facility where by one could add the method you wished to the base class library so that in your project you can use them as if they belong to the base class library. If you have wished something like this then your wish can be fulfilled by Extension Methods. Extension methods in simple terms are the ability to add user defined methods to base classes/types which can be used as intrinsic methods of the base classes/types. Extension methods are not limited to only system classes they can be added to any class. For example, if you want to add your own method to some third party dll you can very well do it using extension methods. Let's explore an example to understand this concept. One example would be to have a method to check whether a number is even or not. Also we will have another "Add" method on the int datatype which will keep on adding the numbers to the current value.

How to implement Extension Methods?

Extension methods can be implemented using static class, static method and the this keyword. The code to implement Extension methods is shown below

public static class MyExtensionMethods
    {
///<summary>
///
to check numeric or not
///</summary>
///<param name="s"></param>
///<returns></returns>
public static bool IsNumeric(this string s)
        {
           float output;
           return float.TryParse(s, out output);
        }
///<summary>
///
  Converts Enumeration type into a dictionary of names and values
///</summary>
///<param name="t"></param>
///<returns></returns>
public static IDictionary<string, int> EnumToDictionary(thisType t)
        {
if (t == null) throw new NullReferenceException();
if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

string[] names = Enum.GetNames(t);
Array values = Enum.GetValues(t);

return (from i in Enumerable.Range(0, names.Length)
select new { Key = names[i], Value = (int)values.GetValue(i) })
                        .ToDictionary(k => k.Key, k => k.Value);
        }
}

  


Similar Articles