How can I define a template member function in C#
For instance I will fill any collection which supports an Add(...) member function, please check out the sample code below
public class CInternalCollection
{
public static void ExternalCollectionTryOne<T<int>>(ref T<int> ext_col, int para_selection = 0)
{
foreach (int int_value in m_int_col)
{
if (int_value > para_selection)
ext_col.Add(int_value);
}
}
public static void ExternalCollectionTryTwo<T>(ref T ext_col, int para_selection = 0)
{
foreach (int int_value in m_int_col)
{
if (int_value > para_selection)
ext_col.Add(int_value);
}
}
static int[] m_int_col = { 0, -1, -3, 5, 7, -8 };
}
The ExternalCollectionTryOne<...(...) would be the preferred kind, because the int type can be explicit defined, but results in an error:
Type parameter declaration must be an identifier not a type
The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
The ExternalCollectionTryTwo<...(...) results in an error:
'T' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)...
I hope the problem is clear – any suggestions?
----------------------------- edit --------------------------
The answers with the interface ICollection<.. without a template member works fine and thanks all for this hint,
but I still cannot define successfully a member template(generic) function
So a more simpler example ... how can I define this
public class CAddCollectionValues
{
public static void AddInt<T>(ref T number, int selection)
{
T new_T = new T(); //this line is just an easy demonstration to get a compile error with type T
foreach (int i_value in m_int_col)
{
if (i_value > selection)
number += i_value; //again the type T cannot be used
}
}
static int[] m_int_col = { 0, -1, -3, 5, 7, -8 };
}