Further extending C# arrays
In my last post, I showed an extension method for resizing arrays. Today I decided to come up with some more extension methods that I find handy. First up: Fill.
Fill is an extension method I wrote because I’m sick of iterating over arrays to fill them in or alter values. Fill looks like this:
public static void Fill<T>(this T[,] array, Func<int, int, T, T> fill)
{
int width = array.GetLength(0);
int height = array.GetLength(1);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
array[x, y] = fill(x, y, array[x, y]);
}
}
}
You can see that it uses a Func to generate the new values. The Func takes in the x and y indices as well as the existing value at that location in the array, then returns the new value. This can be useful for a number of things. Let’s say I have an array of objects and I just used my Resize method to expand the array. I now have a bunch of null objects in there. I can easily use Fill to fix this:
myArray.Fill((x, y, existing) => existing ?? new MyObject());
How’s that for succinct? It’s also useful for new arrays that you want to populate:
int[,] myArray = new int[10, 10]; myArray.Fill((x, y, existing) => x * y);
So you can easily ignore the existing value and simply return a value to replace the current one.
I have a blast making extension methods even if they aren’t revolutionizing how I write code. I find it gives me a chance to just think up a problem and try to solve it in a clean and simple way. Anyone else find themselves doing this? What extension methods are you writing?
Possibly Related Posts
(Automatically Generated)Resizing 2D arrays
Extension Methods and You
Extending GamePadState
How Not To Write A Game – Everything Changes
Spice up your PC input with extension methods
