How to create a generic method in C# that's all applicable to many types - ints, strings, doubles et
Posted
by satyajit
on Stack Overflow
See other posts from Stack Overflow
or by satyajit
Published on 2010-05-20T20:37:11Z
Indexed on
2010/05/20
20:40 UTC
Read the original article
Hit count: 222
Let's I have a method to remove duplicates in an integer Array
public int[] RemoveDuplicates(int[] elems)
{
HashSet<int> uniques = new HashSet<int>();
foreach (int item in elems)
uniques.Add(item);
elems = new int[uniques.Count];
int cnt = 0;
foreach (var item in uniques)
elems[cnt++] = item;
return elems;
}
How can I make this generic such that now it accepts a string array and remove duplicates in it? How about a double array? I know I am probably mixing things here in between primitive and value types. For your reference the following code won't compile
public List<T> RemoveDuplicates(List<T> elems)
{
HashSet<T> uniques = new HashSet<T>();
foreach (var item in elems)
uniques.Add(item);
elems = new List<T>();
int cnt = 0;
foreach (var item in uniques)
elems[cnt++] = item;
return elems;
}
The reason is that all generic types should be closed at run time. Thanks for you comments
© Stack Overflow or respective owner