Share via

Generic Type Constraint for integral_type

Nathan Sokalski 4,111 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?

Developer technologies | C#
Developer technologies | 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.


1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,086 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.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.