1

I often work with arrays of int/float and other things on a regular basis in C# since they are faster (maybe?) than List. Currently I've got dozens of functions implemented per type:

/// <summary>
/// Checks if the array contains the given value.
/// </summary>
public static bool contains(int[] values, int value) {
    for (int s = 0, sl = values.Length; s < sl; s++) {
        if (values[s] == value) {
            return true;
        }
    }
    return false;
}
/// <summary>
/// Checks if the array contains the given value.
/// </summary>
public static bool contains(float[] values, float value) {
    for (int s = 0, sl = values.Length; s < sl; s++) {
        if (values[s] == value) {
            return true;
        }
    }
    return false;
}

Is there a way to implement these in a generic way? Or is that only possible if I use List<T>?

5
  • 2
    What version of .NET are you using? LINQ has this covered. Commented Dec 3, 2012 at 15:33
  • 1
    "(maybe?)"? You don't know for certain? You really should be testing and benchmarking first. Commented Dec 3, 2012 at 15:34
  • Anything generic that you did would be slower. If you care about the difference between an array and a list (which is tiny) you wouldn't want to deal with the (only slightly more than infintessimal) slowdown of genericizing this. Commented Dec 3, 2012 at 15:34
  • 1
    @Servy in what way would the generic version be slower? each generic function is jitted per type that it is used on so it ought to be exactly as fast as a non generic version. except for minimal differences upon jitting. Commented Dec 3, 2012 at 15:36
  • 1
    @RogerAlsing In general, you're correct, however in the specific case of dealing with numeric types, no. There is no generic constraint that you could add (since the numeric types don't have interfaces for most of their functionality) that expose most of what they do. You'll end up using object.Equals to compare the elements, or worse, using a Func to determine equality, which will be slower than having the parameter typed as i.e. int and using operator ==. Commented Dec 3, 2012 at 15:38

2 Answers 2

3

The System.Array type has a dizzying array of static methods that can help you search, arrange, sort etc your arrays. You definitely do not need to roll your own. These static methods (like Find, FindAll) also accept generic arguments. Here's the list, dumped with the aid of PowerShell:

Name                           Definition                    
----                           ----------                    
AsReadOnly                     static System.Collections.... 
BinarySearch                   static int BinarySearch(ar... 
Clear                          static void Clear(array ar... 
ConstrainedCopy                static void ConstrainedCop... 
ConvertAll                     static TOutput[] ConvertAl... 
Copy                           static void Copy(array sou... 
CreateInstance                 static array CreateInstanc... 
Equals                         static bool Equals(System.... 
Exists                         static bool Exists[T](T[] ... 
Find                           static T Find[T](T[] array... 
FindAll                        static T[] FindAll[T](T[] ... 
FindIndex                      static int FindIndex[T](T[... 
FindLast                       static T FindLast[T](T[] a... 
FindLastIndex                  static int FindLastIndex[T... 
ForEach                        static void ForEach[T](T[]... 
IndexOf                        static int IndexOf(array a... 
LastIndexOf                    static int LastIndexOf(arr... 
ReferenceEquals                static bool ReferenceEqual... 
Resize                         static void Resize[T]([ref... 
Reverse                        static void Reverse(array ... 
Sort                           static void Sort(array arr... 
TrueForAll                     static bool TrueForAll[T](... 
Sign up to request clarification or add additional context in comments.

2 Comments

You call 20 functions a dizzying array? (What if he saw my collection!)
I was concentrating more on the pun on "array" than the method count ;)
2

Thanks @Servy for your corrections :

/// <summary>
/// Checks if the array contains the given value.
/// </summary>
public static bool Contains<T>(T[] values, T value) {
    for (int s = 0, sl = values.Length; s < sl; s++) {
        if (object.Equals(values[s].value)) {
            return true;
        }
    }
    return false;
}

For this kind of things, you may also use Linq :

using System.Linq;
...
var myArray = new float[12];
...
if(myArray.Any(a => a == 2.4))

9 Comments

This won't handle null objects well... (unless you add a where T:struct) If you use the static object.Equals(a,b) it will take care of that.
@Kek add a where T : struct generic constraint! ;)
@Geotarget That would do a reference comparison, not a value comparison, since an unconstrained T is equivalent to object.
@Servy, you are right... This is not perfect code, but adding a where T struct seems a little restrictive. I think it depends on how it is called. I'll let the OP customize this code
@Kek See my edit. Just use object.Equals(a,b) instead of a.Equals(b) and the null check will be properly handled.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.