blah blah blah is here! blah blah » Close

up0down
link

I want to write some extension methods for arrays. I'm not quite sure how to approach this.

Suppose I have an array:

byte[] myArray = new byte[24];
// populate byte array here


I want something like

bool areArraysEqual = myArray.CompareTo(anotherArray);


or

byte[] subArray = myArray.Slice(5,3); // offset 5, 3 items


I want to enforce typing, so that if I use the Slice command I can't assign a byte array's Slice to a string array, for example.

I have code written for these methods, with the following method signature:

public static T[] Slice<T>(T[] inArray, int startOffset, int Length)


and

public static bool Compare<T>(T[] a1, T[] a2)


How can I convert these to extension methods that could be called on an array rather than passing references to arrays into the static methods?

fm

last answered 2 years ago

1 answers

up0down
link

You can do it like this (method implementations just for illustration, not necessarily optimal):

using System;
using ArrayExtensions;

namespace ArrayExtensions
{
public static class Array2
{
public static T[] Slice<T>(this T[] inArray, int startOffset, int Length)
{
T[] outArray = new T[Length];
Array.Copy(inArray, startOffset, outArray, 0, Length);
return outArray;
}

public static bool Compare<T>(this T[] a1, T[] a2)
{
if (a1.Length != a2.Length) return false;
for (int i = 0; i < a1.Length; i++)
{
if (!a1[i].Equals(a2[i])) return false;
}
return true;
}
}
}

class Test
{
static void Main()
{
byte[] myArray = new byte[24];
for(byte b = 0; b < 24; b++) myArray[b] = b;
byte[] anotherArray = new byte[24];
for(byte b = 0; b < 24; b++) anotherArray[b] = b;
bool areArraysEqual = myArray.Compare(anotherArray);
Console.WriteLine(areArraysEqual); // True
anotherArray[23] = 46;
areArraysEqual = myArray.Compare(anotherArray);
Console.WriteLine(areArraysEqual); // False
byte[] subArray = myArray.Slice(5,3); // offset 5, 3 items
foreach(byte b in subArray)Console.Write("{0} ", b);
Console.WriteLine();
Console.ReadKey();
}
}

Feedback