-
February 21st, 2009, 04:07 PM
#1
Parameterized type
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.
-
February 21st, 2009, 05:16 PM
#2
Re: Parameterized type
A better way to do this would be:
Code:
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.
Code:
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);
Last edited by BigEd781; February 21st, 2009 at 05:30 PM.
-
February 21st, 2009, 06:09 PM
#3
Re: Parameterized type
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.
-
February 21st, 2009, 06:43 PM
#4
Re: Parameterized type
A boolean cannot be expressed as a number in C#. So this won't work:
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.
Last edited by BigEd781; February 21st, 2009 at 10:42 PM.
-
February 22nd, 2009, 02:12 AM
#5
Re: Parameterized type
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!
Please rate my post if it was helpful for you. Java, C#, C++, PHP, ASP.NET
SQL Server, MySQL
DirectX
MATH Touraj Ebrahimi
[toraj_e] [at] [yahoo] [dot] [com]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|