Using The New Generic Number Interface In .NET 7


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.

Using the new generic number interface in .NET 7

Using the new generic number interface in .NET 7

Now, add the below code to the “Program.cs” file,

using System.Numerics;
double[] values = new [] {
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,

Using the new generic number interface in .NET 7

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.


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.

Recommended Free Ebook
Similar Articles