Click to See Complete Forum and Search --> : Parameterized type


panteleymon
February 21st, 2009, 03:07 PM
A would be a C++ legitimate template doesn't work in C#:

public void PassDoubleArrayToList<T>( double [] x, List<T> items ) where T : struct
{
for( int i = 0; i < x.Count(); ++i )
{
items.Add( (T) x[i] );
}
}

The compiler complains: error CS0030: Cannot convert type 'double' to 'T'. Is there any work around? I would like to use only numeric types with T: double, int, bool, etc. I have tried a lot of ideas, so a piece of code would be appreciated greatly.

BigEd781
February 21st, 2009, 04:16 PM
A better way to do this would be:


List<double> myList = new List<double>(myDoubleArray);


As for your question, you cannot specify double[] as the Array parameter because you need to fill a List<T>, which could be any struct type, so your array needs to be generic as well. The cast is also unnecessary.


private static void PopList<T>(T[] arry, List<T> list) where T : struct
{
for (int i = 0; i < arry.Length; ++i)
{
list.Add(arry[i]);
}
}


However, T does not need to derive from struct as any object in an array of T can be added to a list of T (that is why there is a default constructor for doing this);

panteleymon
February 21st, 2009, 05:09 PM
Thank you for your reply. Unfortunately, you changed the problem. Indeed, I have to assign only array of doubles either to list of doubles, or integers (with rounding), or Booleans. This is the problem.

BigEd781
February 21st, 2009, 05:43 PM
A boolean cannot be expressed as a number in C#. So this won't work:


if (0) {}


C++ templates != C# Generics
If you need to convert the array, I would look at the static Array.ConvertAll<T,T> method.
I should note that I am no expert here, so someon more experienced than myself may have a better solution for you.

toraj58
February 22nd, 2009, 01:12 AM
Generics are strict and they should be.

assume that some one initialize T with something like Foo type that is a user defined class. then how do you expect that in run-time compiler cast double to Foo!