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
Release: 2025-02-01 23:26:10
Original
188 people have browsed it

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

static bool IntegerFunction<T>(T value) where T : IBinaryInteger<T>
{
    return value > T.Zero;
}
Copy after login
<史> Historical background

Console.WriteLine(IntegerFunction(5));         // True
Console.WriteLine(IntegerFunction((sbyte)-5)); // False
Console.WriteLine(IntegerFunction((ulong)5));  // True
Copy after login
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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template