Introduction
Microsoft has just released .NET 7 on 14th November 2022. In other articles, we looked at some of the new features.
Today, we will look at another feature introduced with .NET 7 and that is the generic number interface. Let us begin.
The generic number interface feature
Let us create a console application using Visual Studio 2022 Community edition.
Now, add the below code to the “Program.cs” file,
using System.Numerics;
double[] values = new [] {
100,
50,
-75,
102.50,
-77.50
};
Console.WriteLine(AddAllNumbers(values));
T AddAllNumbers < T > (T[] numbers) where T: INumber < T > {
T sumOfPositiveNumbers = T.Zero;
foreach(var number in numbers) {
if (T.IsPositive(number)) {
sumOfPositiveNumbers += number;
}
}
return sumOfPositiveNumbers;
}
When you run this application, you get the below,
Here, we see that we have created a generic function to add all values of an array that are positive. For this, we are using the new “INumber” interface. In this way, we can handle both integer and double values and hence we do not need to maintain two different functions for these two types.
Summary
In this article, we looked at a new feature that has been introduced with .NET 7. Using the “INumber” interface will help us to design generic functions to handle numbers. In the next article, we will look into another feature of .NET 7.