How to costraint a generics to be a number

  • Thread starter Thread starter Matteo Migliore
  • Start date Start date
M

Matteo Migliore

Hi.

I want to costraint a generics T to be a number (Int32, Double, Byte etc...)
but
how I can do?

I need beacuse I want to use arithmetic operators (+, -...).

Thx! ;-)
 
Matteo,

You can't, at least not at compile time using constraints. You could
perform a check against the type parameter at run time in the static
constructor for the type and see if it is Int32, Double, etc, etc.
 
I use "where T: IComparable<T>" for this. It seems to work okay. Odds
are you needed it constrained to be a number because you need to use
less than, greater than, or equals on it. All of those are easily
possible with the compare interface.
 
Matteo Migliore said:
Hi.

I want to costraint a generics T to be a number (Int32, Double, Byte
etc...) but
how I can do?

I need beacuse I want to use arithmetic operators (+, -...).

You might be able to use extension methods in .Net 3.5. Somthing like this:

public static int Sum(this MyClass<int> list)
{
int sum = 0;
foreach (int i in list)
sum += i;
return sum;
}

And then use it like this:

MyClass<int> a;
int total = a.Sum();


Peter
 
You might be able to use extension methods in .Net 3.5. Somthing like

Thank you for support :-). I know that is possible in .NET 3.x but
I needed to solve problem writing a class.

I solved thanks again! ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top