C
C#3y ago
Nora

✅ Using System.Collections.Generic Wide-ranging Type? (T), but limiting to fewer options

For example, I'd like to create an Add method, that works for int, double, decimal and float. I'd write
public static T Add<T>(T a, T b)
{
return (a+b);
}
public static T Add<T>(T a, T b)
{
return (a+b);
}
But how do I limit T to only the aforementioned four numeric types? Relevant information is appreciated!
12 Replies
Thinker
Thinker3y ago
If you're using .NET 7
using System.Numerics;

public static T Add<T>(T a, T b) where T : INumber<T>
{
return a + b;
}
using System.Numerics;

public static T Add<T>(T a, T b) where T : INumber<T>
{
return a + b;
}
Nora
NoraOP3y ago
I'm using .NET 8.0
Thinker
Thinker3y ago
Preview?
Nora
NoraOP3y ago
Sorry, what do you mean?
Thinker
Thinker3y ago
The latest stable .NET version is 7 So if you're using .NET 8 it's a beta/preview version In any case, if you're using a version >= 7 then INumber<T> should be available
Nora
NoraOP3y ago
Oh, might be. I read in the "terminal?" that "XYZ feature isn't available in .NET 8.0, only available in .NET 9.0", not the exact wording, but you get it.
Thinker
Thinker3y ago
Okay, can you do dotnet --list-sdks and post the output
Nora
NoraOP3y ago
Oh, I've seen the "where" keyword occasionally on Microsoft examples, seems like would be an interesting thing to learn Sure
Thinker
Thinker3y ago
Actually I think you're just using a lower language version. That error occurs when you try using a feature from a language version that is greater than the one you're currently using.
Nora
NoraOP3y ago
lmao, it is 5.0.408 😂
Thinker
Thinker3y ago
yeah there's issue #1 probably As mentioned, .NET 7 is the latest version, there's no reason to use 5 anymore
Nora
NoraOP3y ago
Thanks! I'll try to update it If my potato laptop doesn't crash by then

Did you find this page helpful?