Home >Backend Development >C++ >Can C# Generics Constrain Type Arguments to Specific Integer 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!