Home >Backend Development >C++ >How Can I Constrain Generic Types in .NET to Only Accept Numeric Types?

How Can I Constrain Generic Types in .NET to Only Accept Numeric Types?

Patricia Arquette
Patricia ArquetteOriginal
2025-02-01 23:36:13983browse

How Can I Constrain Generic Types in .NET to Only Accept Numeric Types?

Restricting .NET Generics to Numeric Types

.NET generics provide type flexibility, but often require type constraints. A frequent need is to limit generic type arguments to numeric types like Int16, Int32, Int64, UInt16, UInt32, and UInt64.

The Solution with .NET 7

While earlier versions lacked a direct solution, .NET 7 introduces INumber<T> (in System.Numerics) as the most comprehensive interface for all numeric types. For integer types specifically, IBinaryInteger<T> is available.

Code Example: Integer Function

This example demonstrates an IntegerFunction using IBinaryInteger<T>:

<code class="language-csharp">static bool IntegerFunction<T>(T value) where T : IBinaryInteger<T>
{
    return value > T.Zero;
}</code>

Usage:

<code class="language-csharp">Console.WriteLine(IntegerFunction(5));         // True
Console.WriteLine(IntegerFunction((sbyte)-5)); // False
Console.WriteLine(IntegerFunction((ulong)5));  // True</code>

Pre-.NET 7 Approaches

Before .NET 7, achieving this constraint was more challenging. Methods like using a factory pattern with a Calculator<T> class were suggested, but these resulted in less elegant and less extensible code.

The above is the detailed content of How Can I Constrain Generic Types in .NET to Only Accept Numeric Types?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn