I have an extension for string arrays which returns an empty String if the array is null, if the array length is == 1 it returns the first element otherwise element at index position is returned, no boundaries checking.
public static Strings IndexOrDefault(this String[] arr, Int32 index) { if (arr == null) return String.Empty; return arr.Length == 1 ? arr[0] : arr[index]; } Now, I need to extend this functionality to other arrays, so I figured this extension method could do the job
public static T IndexOrDefault<T>(this T[] arr, Int32 index) { if (arr == null) return default(T); return arr.Length == 1 ? arr[0] : arr[index]; } And everything was fine except default(String) is not String.Empty but null. So I'm returning nulls now for Strings, which was the first requirement...
Is there a replacement for default there that could return an empty generic value instead of a null?
Edit 2: (first one was the definition)
I'm using this approach now, which it works, but it's not as elegant as I wanted (well, the method is not elegant either, but the solution could :) )
public static T IndexOrDefault<T>(this T[] arr, Int32 index) { if (arr == null) return default(T); return arr.Length == 1 ? arr[0] : arr[index]; } public static String IndexOrDefault(this String[] arr, Int32 index) { if (arr == null) return String.Empty; return arr.Length == 1 ? arr[0] : arr[index]; } Two different methods, one for String and the generic one for the rest.
nullfrom a method namedWhateverOrDefaultfor a reference type would be confusing, unintuitive, and honestly an outright lie. Your method says one thing, you are doing another.nullis the default forstring, notString.Empty. Also, why swallow an error by returningarray[0]if the length is1? If the caller is passing an invalid index then they should know about it, not spend time (potentially) trying to find a hidden bug.