Pranay Rana: Extende Array Class with Extension method

Saturday, May 12, 2012

Extende Array Class with Extension method

Read before start reading post : Extension Methods

Here I am going to discuss about the how you can create the Extension method for the System.Array Class. On MSDN : Array Class - Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime

Note - in example below I use type int but this can be replace by any type you want.
In following Example I have implemented Average method for the array elements of type int.
    public static class ArryaExtension
        public static float Average(this System.Array arr)
            int[] a =  arr.Cast().ToArray();
            return (float)a.Sum()/arr.Length;
To get this extension method work you need to pass the type in type as System.Array. Next I converted the array element to type I want this help me to get the support of IEnumerableinterface methods because System.Array is base class which doesn't implement IEnumerable. So once it get convert to specific type array I can able to access IEnumerable methods like Sum which makes task easy.

You can replace the code in the method for any other type and extend the System.Array class easily as per you requirement.


  1. This is wrong design with many loopholes. Your Extension method must explicitly mention that it is only for int[]. And if it is meant to work for int[] then there's no point in making it around Array type. Remember, your code is not just supposed to do the work, It is supposed to work for other programmers. Ask yourself these question and come up with better version of the same method.

    1.) What the extension is supposed to do ? Functional specs of the method.

    2.) Why do you want to make it as an Extension method ?

    3.) What purpose will it serve for other programmers ? In other words, what is the intended use of the Extension method ?

    4.) Type safety ?? General compatibility ??

    5.) What part of your personal code library will it belong to ?

    Hope you'll take this positively and publish a better version.

    - Ruchit.

  2. A better type-safe less complicated version..

    public static float Average(this IEnumerable numbers)
    return (float)numbers.Sum() / numbers.Count();