C
C#2y 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
Thinker2y 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
NoraOP2y ago
I'm using .NET 8.0
Thinker
Thinker2y ago
Preview?
Nora
NoraOP2y ago
Sorry, what do you mean?
Thinker
Thinker2y 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
NoraOP2y 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
Thinker2y ago
Okay, can you do dotnet --list-sdks and post the output
Nora
NoraOP2y ago
Oh, I've seen the "where" keyword occasionally on Microsoft examples, seems like would be an interesting thing to learn Sure
Thinker
Thinker2y 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
NoraOP2y ago
lmao, it is 5.0.408 😂
Thinker
Thinker2y ago
yeah there's issue #1 probably As mentioned, .NET 7 is the latest version, there's no reason to use 5 anymore
Nora
NoraOP2y ago
Thanks! I'll try to update it If my potato laptop doesn't crash by then
Want results from more Discord servers?
Add your server