I would like to write a C# extension for generic Array but it’s always casting an Error. Here is the code i used to create extendsion for string[] which works well :
public static string[] Add(this string[] list, string s, bool checkUnique = false, bool checkNull = true){
if (checkNull && string.IsNullOrEmpty(s)) return list;
if (checkUnique && list.IndexOf(s) != -1) return list;
ArrayList arr = new ArrayList();
arr.AddRange(list);
arr.Add(s);
return (string[])arr.ToArray(typeof(string));
}
What i really want is do it more generic so it will also works for other types not only string (so i tried to replace all string specifics with generics T) :
public static T[] Add(this T[] list, T item, bool checkUnique = false){
if (checkUnique && list.IndexOf(item) != -1) return list;
ArrayList arr = new ArrayList();
arr.AddRange(list);
arr.Add(item);
return (T[])arr.ToArray(typeof(T));
}
but the code won’t compile. It’s casting an error “error CS0246: The type or namespace name `T’ could not be found. Are you missing a using directive or an assembly reference?”
I already tried another solution around :
public static void AddIfNotExists<T>(this ICollection<T> coll, T item) {
if (!coll.Contains(item))
coll.Add(item);
}
but it’s casting another error “error CS0308: The non-generic type `System.Collections.ICollection’ cannot be used with the type arguments”
As a side note, I’m using Unity C# (which is compiles against 3.5 I think). Can anyone help me ?
Your last method does not compile because of the missing reference to the System.Collections.Generic namespace. You seem to have included the reference to System.Collections only.