Home of the AlmostImplementedException

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.

Now we take a view at the definition of the Resize-Function.

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:

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:

Share :

, , , ,

Comments are currently closed.