Home >Backend Development >C++ >Can C# Generics Constrain Type Arguments to Specific Integer Types?

Can C# Generics Constrain Type Arguments to Specific Integer Types?

Susan Sarandon
Susan SarandonOriginal
2025-02-01 23:26:10190browse

Can C# Generics Constrain Type Arguments to Specific Integer Types?

C#generic method's constraints of specific numerical types

When using generics in C#, is there a constraint that can limit the type parameter T to only the following values ​​type: int16, int32, int64, UINT16, UINT32, and UINT64?

Answer

In .NET 7, an interface specially used to limit T to numerical types:

in the name space. To accept only the integer type, you can use

. System.Numerics INumber<T> Considering the following Method implementation: IBinaryInteger<T>

How to use examples: IntegerFunction

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

<code class="language-csharp">Console.WriteLine(IntegerFunction(5));         // True
Console.WriteLine(IntegerFunction((sbyte)-5)); // False
Console.WriteLine(IntegerFunction((ulong)5));  // True</code>
Before .NET 7, C#did not provide such constraints. As Anders Hejlsberg explained, the reason is to avoid unnecessary complexity, and the actual benefits are limited.

For scenes that are unavailable directly to support constraints, it is recommended to use alternative methods, such as factory models or strategies.

The above is the detailed content of Can C# Generics Constrain Type Arguments to Specific Integer 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