I have an extension for string arrays that returns an empty string if the array is null, if the length of the array is == 1, it returns the first element, otherwise the element is returned at the index position, without checking the boundaries.
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 decided that this extension method can 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 for default (String) not String.Empty, but null. So I am returning nulls now for Strings, which was the first requirement ...
Is there a default replacement there that can return an empty common value instead of a null?
Edit 2 : (the first was the definition)
Now I use this approach, which it works, but it is not as elegant as I wanted (well, the method is also not elegant, 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 a common for the rest.