Hyun-jik Bae said:
Is that not allowed to assume generic type numeric type? As far as
I've tried, I got an error with the following code:
public class AAA<T>
{
public int Foo(T a)
{
return a; // error: Cannot implicitly convert type 'T' to
'int' }
}
public class BBB
{
public int Goo()
{
int x = 3;
return AAA<int>.Foo(x);
}
}
where my intention is to use AAA<> on numeric value only, which is
acceptable in C++.
How can I resolve that compilation error? Please reply.
Since .NET generics are fully compiled and represented in the IL, in order
for that IL to be verifiable (provably safe), there are limitations on what
..NET generics can do - they are severely limited compared to C++ templates
(and also have significant advantages compared to C++ templates in some
cases).
To use a type as a generic type parameter, when you write the generic class,
you specify constraints on the generic type parameters. These constraints
actually increase what you can do with the type. There are only two types
of constraints: a constructor contraint, written as new(), and an interface
constraint.
Unfortunately, there's no "IConvertsToInt" interface defined by the .NET
framework, and defining such an interface yourself would be unfulfilling at
best.
Your best bet in the example you supplied is probably to use the Convert
class
public class AAA<T>
{
public int Foo(T a)
{
return Convert.ToInt32(a);
}
}
public class BBB
{
public int Goo()
{
int x = 3;
return AAA<int>.Foo(x);
}
}
Unfortunately, this will result in 'a' being boxed onto the managed heap,
since Convert.ToIn32 takes a parameter of type System.Object. But it will
work.
Doing arithmetic - even simple comparisions - with generic parameters is
hard. There are a couple of artibles on code project that explain the
limitations and what you can do to work around them.
Here's one of them - there's at least one other good one, but I couldn't
find it with a quick search.
http://www.codeproject.com/csharp/genericnumerics.asp
-cd