Generic Type Constraint for integral_type

Nathan Sokalski 4,126 Reputation points
2022-05-06T18:52:12.747+00:00

I have a Generic method for which I need to constrain the type to integral_type (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#836-integral-types). However, the best I could find was to use where U : struct, but this allows a lot more than just integral types. Is there a way to constrain the type to integral types?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,602 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 60,866 Reputation points
    2022-05-06T21:38:24.48+00:00

    you can constrain to value types. depending on the parameter mix, you might want to try method overloading:

        private void _CallIntType<T>(T i) =>  Console.WriteLine(i);
    
        public void CallIntType(long i) => _CallIntType(i); 
        public void CallIntType(ulong i) => _CallIntType(i); 
    

    this makes use the compiler up casting.

    0 comments No comments