Extend The Array Class with Extension Methods
Join the DZone community and get the full member experience.
Join For FreeHere I am going to discuss 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
In following Example I have implemented Average method for the array elements of type int.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.
Conclusion
You can replace the code in the method for any other type and extend the System.Array class easily as per you requirement.
public static class ArryaExtension { public static float Average(this System.Array arr) { int[] a = arr.Cast<int>().ToArray(); return (float)a.Sum()/arr.Length; } } </int>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.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.
Conclusion
You can replace the code in the method for any other type and extend the System.Array class easily as per you requirement.
Data structure
Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments