1 02 2013
Introducing Extension Methods for Arrays
With Extension methods you can extend the existing funtionality of objects and types. In this case we will extend the functionality of an Array.
So we need to create two extensions. One for changing the size and one for appending a new element.
What do we need for this? At first we need a static class and we call it ArrayExtensions.
1 2 3 |
public static class ArrayExtensions { } |
Now we take a view at the definition of the Resize-Function.
1 2 3 4 5 |
public static T[] Resize(this T[] Source, int NewSize) { Array.Resize(ref Source, Source.Length + 1); return Source; } |
We will see that we need a return value for the function. Why? An Array is a value type and we aren’t able to modify it directly in the function. Unfortunately it isn’t possible to change the function in a way that we are able to hand over the Array by the ref-keyword. For reference types we can modify the parameter directly in the function without defining a return value.
Keep in mind: When you have an extension method for a value type and you will modify it in the function, you need to provide the changed object as return value. The function call should look like this:
1 2 |
object[] myArray = new object[] { 1, 2, 3 }; myArray = myArray.Resize(4); |
The parameter NewSize is the new size of the array. Furthermore extensions method need to be declared as static. But they will be called with instance method syntax. Like the upper example. The interesting one is the first parameter of the function. It begins with this T[]. That indicates that the function is refering (this) to Array of any Type (T).
The final version of ArrayExtensions looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public static class ArrayExtension { public static T[] Resize(this T[] Source, int NewSize) { Array.Resize(ref Source, Source.Length + 1); return Source; } public static T[] Append(this T[] Source, T NewElement) { Array.Resize(ref Source, Source.Length + 1); Source[Source.Length - 1] = NewElement; return Source; } } |
Comments are currently closed.