<p>Can anyone tell me if there is a way with generics to limit a generic type argument <code>T</code> to only:</p>

<ul>
<li><code>Int16</code></li>
<li><code>Int32</code></li>
<li><code>Int64</code></li>
<li><code>UInt16</code></li>
<li><code>UInt32</code></li>
<li><code>UInt64</code></li>
</ul>

<p>I'm aware of the <code>where</code> keyword, but can't find an interface for <strong>only</strong> these types,</p>

<p>Something like:</p>

<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : INumeric 
</code></pre>

[{'answer_id': 32687, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 7, 'selected': False, 'text': '<p>There\'s no constraint for this. It\'s a real issue for anyone wanting to use generics for numeric calculations.</p>\n\n<p>I\'d go further and say we need</p>\n\n<pre><code>static bool GenericFunction&lt;T&gt;(T value) \n    where T : operators( +, -, /, * )\n</code></pre>\n\n<p>Or even</p>\n\n<pre><code>static bool GenericFunction&lt;T&gt;(T value) \n    where T : Add, Subtract\n</code></pre>\n\n<p>Unfortunately you only have interfaces, base classes and the keywords <code>struct</code> (must be value-type), <code>class</code> (must be reference type) and <code>new()</code> (must have default constructor)</p>\n\n<p>You could wrap the number in something else (similar to <code>INullable&lt;T&gt;</code>) like <a href="http://www.codeproject.com/KB/cs/genericnumerics.aspx" rel="noreferrer">here on codeproject</a>.</p>\n\n<hr>\n\n<p>You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place.</p>\n'}, {'answer_id': 32690, 'author': 'Haacked', 'author_id': 598, 'author_profile': 'https://Stackoverflow.com/users/598', 'pm_score': 4, 'selected': False, 'text': '<p>Probably the closest you can do is </p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T: struct\n</code></pre>\n\n<p>Not sure if you could do the following</p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T: struct, IComparable\n, IFormattable, IConvertible, IComparable&lt;T&gt;, IEquatable&lt;T&gt;\n</code></pre>\n\n<p>For something so specific, why not just have overloads for each type, the list is so short and it would possibly have less memory footprint.</p>\n'}, {'answer_id': 32699, 'author': 'Martin Marconcini', 'author_id': 2684, 'author_profile': 'https://Stackoverflow.com/users/2684', 'pm_score': 2, 'selected': False, 'text': "<p>I was wondering the same as samjudson, why only to integers? and if that is the case, you might want to create a helper class or something like that to hold all the types you want.</p>\n\n<p>If all you want are integers, don't use a generic, that is not generic; or better yet, reject any other type by checking its type. </p>\n"}, {'answer_id': 32727, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 4, 'selected': False, 'text': '<p>Unfortunately you are only able to specify struct in the where clause in this instance. It does seem strange you can\'t specify Int16, Int32, etc. specifically but I\'m sure there\'s some deep implementation reason underlying the decision to not permit value types in a where clause.</p>\n\n<p>I guess the only solution is to do a runtime check which unfortunately prevents the problem being picked up at compile time. That\'d go something like:-</p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : struct {\n  if (typeof(T) != typeof(Int16)  &amp;&amp;\n      typeof(T) != typeof(Int32)  &amp;&amp;\n      typeof(T) != typeof(Int64)  &amp;&amp;\n      typeof(T) != typeof(UInt16) &amp;&amp;\n      typeof(T) != typeof(UInt32) &amp;&amp;\n      typeof(T) != typeof(UInt64)) {\n    throw new ArgumentException(\n      string.Format("Type \'{0}\' is not valid.", typeof(T).ToString()));\n  }\n\n  // Rest of code...\n}\n</code></pre>\n\n<p>Which is a little bit ugly I know, but at least provides the required constraints.</p>\n\n<p>I\'d also look into possible performance implications for this implementation, perhaps there\'s a faster way out there.</p>\n'}, {'answer_id': 33383, 'author': 'dbkk', 'author_id': 838, 'author_profile': 'https://Stackoverflow.com/users/838', 'pm_score': 1, 'selected': False, 'text': '<p>What is the point of the exercise?</p>\n\n<p>As people pointed out already, you could have a non-generic function taking the largest item, and compiler will automatically convert up smaller ints for you. </p>\n\n<pre><code>static bool IntegerFunction(Int64 value) { }\n</code></pre>\n\n<p>If your function is on performance-critical path (very unlikely, IMO), you could provide overloads for all needed functions.</p>\n\n<pre><code>static bool IntegerFunction(Int64 value) { }\n...\nstatic bool IntegerFunction(Int16 value) { }\n</code></pre>\n'}, {'answer_id': 34186, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 7, 'selected': False, 'text': '<p>More than a decade later, this feature finally exists in <a href="https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/" rel="nofollow noreferrer">.NET 7</a>. The most generic interface is <code>INumber&lt;TSelf&gt;</code> rather than <code>INumeric</code> (in the <code>System.Numerics</code> namespace), and it encompasses not just integer types. To accept just integer types, consider using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.numerics.ibinaryinteger-1?view=net-7.0" rel="nofollow noreferrer"><code>IBinaryInteger&lt;TSelf&gt;</code></a> instead. To use the example of your prototypical, mystical <code>IntegerFunction</code>:</p>\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : IBinaryInteger&lt;T&gt; {\n    return value &gt; T.Zero;\n}\n</code></pre>\n<pre><code>Console.WriteLine(IntegerFunction(5));         // True\nConsole.WriteLine(IntegerFunction((sbyte)-5)); // False\nConsole.WriteLine(IntegerFunction((ulong)5));  // True\n</code></pre>\n<hr />\n<p>The (now obsolete) answer below is left as a historical perspective.</p>\n<p>C# does not support this. Hejlsberg has described the reasons for not implementing the feature <a href="http://www.artima.com/intv/generics.html" rel="nofollow noreferrer">in an interview with Bruce Eckel</a>:</p>\n<blockquote>\n<p>And it\'s not clear that the added complexity is worth the small yield that you get. If something you want to do is not directly supported in the constraint system, you can do it with a factory pattern. You could have a <code>Matrix&lt;T&gt;</code>, for example, and in that <code>Matrix</code> you would like to define a dot product method. That of course that means you ultimately need to understand how to multiply two <code>T</code>s, but you can\'t say that as a constraint, at least not if <code>T</code> is <code>int</code>, <code>double</code>, or <code>float</code>. But what you could do is have your <code>Matrix</code> take as an argument a <code>Calculator&lt;T&gt;</code>, and in <code>Calculator&lt;T&gt;</code>, have a method called <code>multiply</code>. You go implement that and you pass it to the <code>Matrix</code>.</p>\n</blockquote>\n<p>However, this leads to fairly convoluted code, where the user has to supply their own <code>Calculator&lt;T&gt;</code> implementation, for each <code>T</code> that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such as <code>int</code> and <code>double</code>, you can get away with a relatively simple interface:</p>\n<pre class="lang-cs prettyprint-override"><code>var mat = new Matrix&lt;int&gt;(w, h);\n</code></pre>\n<p>(<a href="https://gist.github.com/klmr/314d05b66c72d62bd8a184514568e22f" rel="nofollow noreferrer">Minimal implementation in a GitHub Gist.</a>)</p>\n<p>However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own <code>Calculator</code> instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation, <code>DFP</code>, you’d have to write this code:</p>\n<pre class="lang-cs prettyprint-override"><code>var mat = new Matrix&lt;DFP&gt;(DfpCalculator.Instance, w, h);\n</code></pre>\n<p>… and implement all the members for <code>DfpCalculator : ICalculator&lt;DFP&gt;</code>.</p>\n<p>An alternative, which unfortunately shares the same limitations, is to work with policy classes, <a href="https://stackoverflow.com/a/4834066/1968">as discussed in Sergey Shandar’s answer</a>.</p>\n'}, {'answer_id': 1268443, 'author': 'Marc Gravell', 'author_id': 23354, 'author_profile': 'https://Stackoverflow.com/users/23354', 'pm_score': 4, 'selected': False, 'text': '<p>This question is a bit of a FAQ one, so I\'m posting this as wiki (since I\'ve posted similar before, but this is an older one); anyway...</p>\n<p>What version of .NET are you using? If you are using .NET 3.5, then I have a <a href="https://jonskeet.uk/csharp/genericoperators.html" rel="nofollow noreferrer">generic operators implementation</a> in <a href="https://jonskeet.uk/csharp/miscutil/index.html" rel="nofollow noreferrer">MiscUtil</a> (free etc).</p>\n<p>This has methods like <code>T Add&lt;T&gt;(T x, T y)</code>, and other variants for arithmetic on different types (like <code>DateTime + TimeSpan</code>).</p>\n<p>Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.</p>\n<p>Some additional background on why this is tricky is <a href="https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html" rel="nofollow noreferrer">here</a>.</p>\n<p>You may also want to know that <code>dynamic</code> (4.0) sort-of solves this issue indirectly too - i.e.</p>\n<pre><code>dynamic x = ..., y = ...\ndynamic result = x + y; // does what you expect\n</code></pre>\n'}, {'answer_id': 2065410, 'author': 'Marc Roussel', 'author_id': 250846, 'author_profile': 'https://Stackoverflow.com/users/250846', 'pm_score': 1, 'selected': False, 'text': '<p>I would use a generic one which you could handle externaly...</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Generic object copy of the same type\n/// &lt;/summary&gt;\n/// &lt;typeparam name="T"&gt;The type of object to copy&lt;/typeparam&gt;\n/// &lt;param name="ObjectSource"&gt;The source object to copy&lt;/param&gt;\npublic T CopyObject&lt;T&gt;(T ObjectSource)\n{\n    T NewObject = System.Activator.CreateInstance&lt;T&gt;();\n\n    foreach (PropertyInfo p in ObjectSource.GetType().GetProperties())\n        NewObject.GetType().GetProperty(p.Name).SetValue(NewObject, p.GetValue(ObjectSource, null), null);\n\n    return NewObject;\n}\n</code></pre>\n'}, {'answer_id': 4188702, 'author': 'pomeroy', 'author_id': 141635, 'author_profile': 'https://Stackoverflow.com/users/141635', 'pm_score': 1, 'selected': False, 'text': '<p>This limitation affected me when I tried to overload operators for generic types; since there was no "INumeric" constraint, and for a bevy of other reasons the good people on stackoverflow are happy to provide, operations cannot be defined on generic types.</p>\n\n<p>I wanted something like</p>\n\n<pre><code>public struct Foo&lt;T&gt;\n{\n    public T Value{ get; private set; }\n\n    public static Foo&lt;T&gt; operator +(Foo&lt;T&gt; LHS, Foo&lt;T&gt; RHS)\n    {\n        return new Foo&lt;T&gt; { Value = LHS.Value + RHS.Value; };\n    }\n}\n</code></pre>\n\n<p>I have worked around this issue using .net4 dynamic runtime typing.  </p>\n\n<pre><code>public struct Foo&lt;T&gt;\n{\n    public T Value { get; private set; }\n\n    public static Foo&lt;T&gt; operator +(Foo&lt;T&gt; LHS, Foo&lt;T&gt; RHS)\n    {\n        return new Foo&lt;T&gt; { Value = LHS.Value + (dynamic)RHS.Value };\n    }\n}\n</code></pre>\n\n<p>The two things about using <code>dynamic</code> are </p>\n\n<ol>\n<li>Performance.  All value types get boxed.</li>\n<li>Runtime errors.  You "beat" the compiler, but lose type safety.  If the generic type doesn\'t have the operator defined, an exception will be thrown during execution.</li>\n</ol>\n'}, {'answer_id': 4834066, 'author': 'Sergey Shandar', 'author_id': 374845, 'author_profile': 'https://Stackoverflow.com/users/374845', 'pm_score': 6, 'selected': False, 'text': '<p>Workaround using policies:</p>\n\n<pre><code>interface INumericPolicy&lt;T&gt;\n{\n    T Zero();\n    T Add(T a, T b);\n    // add more functions here, such as multiplication etc.\n}\n\nstruct NumericPolicies:\n    INumericPolicy&lt;int&gt;,\n    INumericPolicy&lt;long&gt;\n    // add more INumericPolicy&lt;&gt; for different numeric types.\n{\n    int INumericPolicy&lt;int&gt;.Zero() { return 0; }\n    long INumericPolicy&lt;long&gt;.Zero() { return 0; }\n    int INumericPolicy&lt;int&gt;.Add(int a, int b) { return a + b; }\n    long INumericPolicy&lt;long&gt;.Add(long a, long b) { return a + b; }\n    // implement all functions from INumericPolicy&lt;&gt; interfaces.\n\n    public static NumericPolicies Instance = new NumericPolicies();\n}\n</code></pre>\n\n<p>Algorithms:</p>\n\n<pre><code>static class Algorithms\n{\n    public static T Sum&lt;P, T&gt;(this P p, params T[] a)\n        where P: INumericPolicy&lt;T&gt;\n    {\n        var r = p.Zero();\n        foreach(var i in a)\n        {\n            r = p.Add(r, i);\n        }\n        return r;\n    }\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>int i = NumericPolicies.Instance.Sum(1, 2, 3, 4, 5);\nlong l = NumericPolicies.Instance.Sum(1L, 2, 3, 4, 5);\nNumericPolicies.Instance.Sum("www", "") // compile-time error.\n</code></pre>\n\n<p>The solution is compile-time safe. <a href="http://citylizard.codeplex.com/releases/view/60527" rel="noreferrer">CityLizard Framework</a> provides compiled version for .NET 4.0. The file is lib/NETFramework4.0/CityLizard.Policy.dll.</p>\n\n<p>It\'s also available in Nuget: <a href="https://www.nuget.org/packages/CityLizard/" rel="noreferrer">https://www.nuget.org/packages/CityLizard/</a>. See <strong>CityLizard.Policy.I</strong> structure.</p>\n'}, {'answer_id': 6549763, 'author': 'dmihailescu', 'author_id': 376495, 'author_profile': 'https://Stackoverflow.com/users/376495', 'pm_score': 2, 'selected': False, 'text': "<p>There is no 'good' solution for this yet. However you can narrow the type argument significantly to rule out many missfits for your hypotetical 'INumeric' constraint as Haacked has shown above.</p>\n\n<p>static bool IntegerFunction&lt;T&gt;(T value) where T: IComparable, IFormattable, IConvertible, IComparable&lt;T&gt;, IEquatable&lt;T&gt;, struct \n{... </p>\n"}, {'answer_id': 16402309, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 1, 'selected': False, 'text': '<p>The .NET numeric primitive types do not share any common interface that would allow them to be used for calculations.  It would be possible to define your own interfaces (e.g. <code>ISignedWholeNumber</code>) which would perform such operations, define structures which contain a single <code>Int16</code>, <code>Int32</code>, etc. and implement those interfaces, and then have methods which accept generic types constrained to <code>ISignedWholeNumber</code>, but having to convert numeric values to your structure types would likely be a nuisance.</p>\n\n<p>An alternative approach would be to define static class <code>Int64Converter&lt;T&gt;</code> with a static property <code>bool Available {get;};</code> and static delegates for <code>Int64 GetInt64(T value)</code>, <code>T FromInt64(Int64 value)</code>, <code>bool TryStoreInt64(Int64 value, ref T dest)</code>.  The class constructor could use be hard-coded to load delegates for known types, and possibly use Reflection to test whether type <code>T</code> implements methods with the proper names and signatures (in case it\'s something like a struct which contains an <code>Int64</code> and represents a number, but has a custom <code>ToString()</code> method).  This approach would lose the advantages associated with compile-time type-checking, but would still manage to avoid boxing operations and each type would only have to be "checked" once.  After that, operations associated with that type would be replaced with a delegate dispatch.</p>\n'}, {'answer_id': 16481028, 'author': 'Martin Mulder', 'author_id': 2304116, 'author_profile': 'https://Stackoverflow.com/users/2304116', 'pm_score': 2, 'selected': False, 'text': '<p>I created a little library functionality to solve these problems:</p>\n\n<p>Instead of:</p>\n\n<pre><code>public T DifficultCalculation&lt;T&gt;(T a, T b)\n{\n    T result = a * b + a; // &lt;== WILL NOT COMPILE!\n    return result;\n}\nConsole.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.\n</code></pre>\n\n<p>You could write:</p>\n\n<pre><code>public T DifficultCalculation&lt;T&gt;(Number&lt;T&gt; a, Number&lt;T&gt; b)\n{\n    Number&lt;T&gt; result = a * b + a;\n    return (T)result;\n}\nConsole.WriteLine(DifficultCalculation(2, 3)); // Results in 8.\n</code></pre>\n\n<p>You can find the source code here: <a href="https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number">https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number</a></p>\n'}, {'answer_id': 22425077, 'author': 'Jeroen Vannevel', 'author_id': 1864167, 'author_profile': 'https://Stackoverflow.com/users/1864167', 'pm_score': 7, 'selected': False, 'text': '<p>Considering the popularity of this question and the interest behind such a function I am surprised to see that there is no answer involving T4 yet.</p>\n\n<p>In this sample code I will demonstrate a very simple example of how you can use the powerful templating engine to do what the compiler pretty much does behind the scenes with generics.</p>\n\n<p>Instead of going through hoops and sacrificing compile-time certainty you can simply generate the function you want for every type you like and use that accordingly (at compile time!).</p>\n\n<p>In order to do this: </p>\n\n<ul>\n<li>Create a new <em>Text Template</em> file called <em>GenericNumberMethodTemplate.tt</em>. </li>\n<li>Remove the auto-generated code (you\'ll keep most of it, but some isn\'t needed).</li>\n<li>Add the following snippet:</li>\n</ul>\n\n<pre class="lang-none prettyprint-override"><code>&lt;#@ template language="C#" #&gt;\n&lt;#@ output extension=".cs" #&gt;\n&lt;#@ assembly name="System.Core" #&gt;\n\n&lt;# Type[] types = new[] {\n    typeof(Int16), typeof(Int32), typeof(Int64),\n    typeof(UInt16), typeof(UInt32), typeof(UInt64)\n    };\n#&gt;\n\nusing System;\npublic static class MaxMath {\n    &lt;# foreach (var type in types) { \n    #&gt;\n        public static &lt;#= type.Name #&gt; Max (&lt;#= type.Name #&gt; val1, &lt;#= type.Name #&gt; val2) {\n            return val1 &gt; val2 ? val1 : val2;\n        }\n    &lt;#\n    } #&gt;\n}\n</code></pre>\n\n<p>That\'s it. You\'re done now.</p>\n\n<p>Saving this file will automatically compile it to this source file:</p>\n\n<pre><code>using System;\npublic static class MaxMath {\n    public static Int16 Max (Int16 val1, Int16 val2) {\n        return val1 &gt; val2 ? val1 : val2;\n    }\n    public static Int32 Max (Int32 val1, Int32 val2) {\n        return val1 &gt; val2 ? val1 : val2;\n    }\n    public static Int64 Max (Int64 val1, Int64 val2) {\n        return val1 &gt; val2 ? val1 : val2;\n    }\n    public static UInt16 Max (UInt16 val1, UInt16 val2) {\n        return val1 &gt; val2 ? val1 : val2;\n    }\n    public static UInt32 Max (UInt32 val1, UInt32 val2) {\n        return val1 &gt; val2 ? val1 : val2;\n    }\n    public static UInt64 Max (UInt64 val1, UInt64 val2) {\n        return val1 &gt; val2 ? val1 : val2;\n    }\n}\n</code></pre>\n\n<p>In your <code>main</code> method you can verify that you have compile-time certainty:</p>\n\n<pre><code>namespace TTTTTest\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            long val1 = 5L;\n            long val2 = 10L;\n            Console.WriteLine(MaxMath.Max(val1, val2));\n            Console.Read();\n        }\n    }\n}\n</code></pre>\n\n<p><img src="https://i.stack.imgur.com/300td.png" alt="enter image description here"></p>\n\n<p>I\'ll get ahead of one remark: no, this is not a violation of the DRY principle. The DRY principle is there to prevent people from duplicating code in multiple places that would cause the application to become hard to maintain.</p>\n\n<p>This is not at all the case here: if you want a change then you can just change the template (a single source for all your generation!) and it\'s done.</p>\n\n<p>In order to use it with your own custom definitions, add a namespace declaration (make sure it\'s the same one as the one where you\'ll define your own implementation) to your generated code and mark the class as <code>partial</code>. Afterwards, add these lines to your template file so it will be included in the eventual compilation:</p>\n\n<pre class="lang-none prettyprint-override"><code>&lt;#@ import namespace="TheNameSpaceYouWillUse" #&gt;\n&lt;#@ assembly name="$(TargetPath)" #&gt;\n</code></pre>\n\n<p>Let\'s be honest: This is pretty cool.</p>\n\n<p>Disclaimer: this sample has been heavily influenced by <a href="http://www.manning.com/hazzard/" rel="noreferrer">Metaprogramming in .NET by Kevin Hazzard and Jason Bock, Manning Publications</a>.</p>\n'}, {'answer_id': 27627106, 'author': 'Rob Deary', 'author_id': 1977538, 'author_profile': 'https://Stackoverflow.com/users/1977538', 'pm_score': 3, 'selected': False, 'text': '<p>There is no way to restrict templates to types, but you can define different actions based on the type.  As part of a generic numeric package, I needed a generic class to add two values.   </p>\n\n<pre><code>    class Something&lt;TCell&gt;\n    {\n        internal static TCell Sum(TCell first, TCell second)\n        {\n            if (typeof(TCell) == typeof(int))\n                return (TCell)((object)(((int)((object)first)) + ((int)((object)second))));\n\n            if (typeof(TCell) == typeof(double))\n                return (TCell)((object)(((double)((object)first)) + ((double)((object)second))));\n\n            return second;\n        }\n    }\n</code></pre>\n\n<p>Note that the typeofs are evaluated at compile time, so the if statements would be removed by the compiler. The compiler also removes spurious casts.  So Something would resolve in the compiler to </p>\n\n<pre><code>        internal static int Sum(int first, int second)\n        {\n            return first + second;\n        }\n</code></pre>\n'}, {'answer_id': 45775531, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>If you are using .NET 4.0 and later then you can just use <strong>dynamic</strong> as method argument and check <strong>in runtime</strong> that the passed <strong>dynamic</strong> argument type is numeric/integer type.</p>\n\n<p>If the type of the passed <strong>dynamic</strong> is <strong>not</strong> numeric/integer type then throw exception.</p>\n\n<p>An example <strong>short</strong> code that implements the idea is something like:</p>\n\n<pre><code>using System;\npublic class InvalidArgumentException : Exception\n{\n    public InvalidArgumentException(string message) : base(message) {}\n}\npublic class InvalidArgumentTypeException : InvalidArgumentException\n{\n    public InvalidArgumentTypeException(string message) : base(message) {}\n}\npublic class ArgumentTypeNotIntegerException : InvalidArgumentTypeException\n{\n    public ArgumentTypeNotIntegerException(string message) : base(message) {}\n}\npublic static class Program\n{\n    private static bool IntegerFunction(dynamic n)\n    {\n        if (n.GetType() != typeof(Int16) &amp;&amp;\n            n.GetType() != typeof(Int32) &amp;&amp;\n            n.GetType() != typeof(Int64) &amp;&amp;\n            n.GetType() != typeof(UInt16) &amp;&amp;\n            n.GetType() != typeof(UInt32) &amp;&amp;\n            n.GetType() != typeof(UInt64))\n            throw new ArgumentTypeNotIntegerException("argument type is not integer type");\n        //code that implements IntegerFunction goes here\n    }\n    private static void Main()\n    {\n         Console.WriteLine("{0}",IntegerFunction(0)); //Compiles, no run time error and first line of output buffer is either "True" or "False" depends on the code that implements "Program.IntegerFunction" static method.\n         Console.WriteLine("{0}",IntegerFunction("string")); //Also compiles but it is run time error and exception of type "ArgumentTypeNotIntegerException" is thrown here.\n         Console.WriteLine("This is the last Console.WriteLine output"); //Never reached and executed due the run time error and the exception thrown on the second line of Program.Main static method.\n    }\n</code></pre>\n\n<p>Of course that this solution works in run time only but never in compile time.</p>\n\n<p>If you want a solution that always works in compile time and never in run time then you will have to wrap the <strong>dynamic</strong> with a public struct/class whose overloaded <strong>public</strong> constructors accept arguments of the desired types only and give the struct/class appropriate name.</p>\n\n<p>It makes sense that the wrapped <strong>dynamic</strong> is always <strong>private</strong> member of the class/struct and it is the only member of the struct/class and the name of the only member of the struct/class is "value".</p>\n\n<p>You will also have to define and implement <strong>public</strong> methods and/or operators that work with the desired types for the private dynamic member of the class/struct if necessary.</p>\n\n<p>It also makes sense that the struct/class has <strong>special/unique</strong> constructor that accepts <strong>dynamic</strong> as argument that initializes it\'s only private dynamic member called "value" but the <strong>modifier</strong> of this constructor is <strong>private</strong> of course.</p>\n\n<p>Once the class/struct is ready define the argument\'s type of IntegerFunction to be that class/struct that has been defined.</p>\n\n<p>An example <strong>long</strong> code that implements the idea is something like:</p>\n\n<pre><code>using System;\npublic struct Integer\n{\n    private dynamic value;\n    private Integer(dynamic n) { this.value = n; }\n    public Integer(Int16 n) { this.value = n; }\n    public Integer(Int32 n) { this.value = n; }\n    public Integer(Int64 n) { this.value = n; }\n    public Integer(UInt16 n) { this.value = n; }\n    public Integer(UInt32 n) { this.value = n; }\n    public Integer(UInt64 n) { this.value = n; }\n    public Integer(Integer n) { this.value = n.value; }\n    public static implicit operator Int16(Integer n) { return n.value; }\n    public static implicit operator Int32(Integer n) { return n.value; }\n    public static implicit operator Int64(Integer n) { return n.value; }\n    public static implicit operator UInt16(Integer n) { return n.value; }\n    public static implicit operator UInt32(Integer n) { return n.value; }\n    public static implicit operator UInt64(Integer n) { return n.value; }\n    public static Integer operator +(Integer x, Int16 y) { return new Integer(x.value + y); }\n    public static Integer operator +(Integer x, Int32 y) { return new Integer(x.value + y); }\n    public static Integer operator +(Integer x, Int64 y) { return new Integer(x.value + y); }\n    public static Integer operator +(Integer x, UInt16 y) { return new Integer(x.value + y); }\n    public static Integer operator +(Integer x, UInt32 y) { return new Integer(x.value + y); }\n    public static Integer operator +(Integer x, UInt64 y) { return new Integer(x.value + y); }\n    public static Integer operator -(Integer x, Int16 y) { return new Integer(x.value - y); }\n    public static Integer operator -(Integer x, Int32 y) { return new Integer(x.value - y); }\n    public static Integer operator -(Integer x, Int64 y) { return new Integer(x.value - y); }\n    public static Integer operator -(Integer x, UInt16 y) { return new Integer(x.value - y); }\n    public static Integer operator -(Integer x, UInt32 y) { return new Integer(x.value - y); }\n    public static Integer operator -(Integer x, UInt64 y) { return new Integer(x.value - y); }\n    public static Integer operator *(Integer x, Int16 y) { return new Integer(x.value * y); }\n    public static Integer operator *(Integer x, Int32 y) { return new Integer(x.value * y); }\n    public static Integer operator *(Integer x, Int64 y) { return new Integer(x.value * y); }\n    public static Integer operator *(Integer x, UInt16 y) { return new Integer(x.value * y); }\n    public static Integer operator *(Integer x, UInt32 y) { return new Integer(x.value * y); }\n    public static Integer operator *(Integer x, UInt64 y) { return new Integer(x.value * y); }\n    public static Integer operator /(Integer x, Int16 y) { return new Integer(x.value / y); }\n    public static Integer operator /(Integer x, Int32 y) { return new Integer(x.value / y); }\n    public static Integer operator /(Integer x, Int64 y) { return new Integer(x.value / y); }\n    public static Integer operator /(Integer x, UInt16 y) { return new Integer(x.value / y); }\n    public static Integer operator /(Integer x, UInt32 y) { return new Integer(x.value / y); }\n    public static Integer operator /(Integer x, UInt64 y) { return new Integer(x.value / y); }\n    public static Integer operator %(Integer x, Int16 y) { return new Integer(x.value % y); }\n    public static Integer operator %(Integer x, Int32 y) { return new Integer(x.value % y); }\n    public static Integer operator %(Integer x, Int64 y) { return new Integer(x.value % y); }\n    public static Integer operator %(Integer x, UInt16 y) { return new Integer(x.value % y); }\n    public static Integer operator %(Integer x, UInt32 y) { return new Integer(x.value % y); }\n    public static Integer operator %(Integer x, UInt64 y) { return new Integer(x.value % y); }\n    public static Integer operator +(Integer x, Integer y) { return new Integer(x.value + y.value); }\n    public static Integer operator -(Integer x, Integer y) { return new Integer(x.value - y.value); }\n    public static Integer operator *(Integer x, Integer y) { return new Integer(x.value * y.value); }\n    public static Integer operator /(Integer x, Integer y) { return new Integer(x.value / y.value); }\n    public static Integer operator %(Integer x, Integer y) { return new Integer(x.value % y.value); }\n    public static bool operator ==(Integer x, Int16 y) { return x.value == y; }\n    public static bool operator !=(Integer x, Int16 y) { return x.value != y; }\n    public static bool operator ==(Integer x, Int32 y) { return x.value == y; }\n    public static bool operator !=(Integer x, Int32 y) { return x.value != y; }\n    public static bool operator ==(Integer x, Int64 y) { return x.value == y; }\n    public static bool operator !=(Integer x, Int64 y) { return x.value != y; }\n    public static bool operator ==(Integer x, UInt16 y) { return x.value == y; }\n    public static bool operator !=(Integer x, UInt16 y) { return x.value != y; }\n    public static bool operator ==(Integer x, UInt32 y) { return x.value == y; }\n    public static bool operator !=(Integer x, UInt32 y) { return x.value != y; }\n    public static bool operator ==(Integer x, UInt64 y) { return x.value == y; }\n    public static bool operator !=(Integer x, UInt64 y) { return x.value != y; }\n    public static bool operator ==(Integer x, Integer y) { return x.value == y.value; }\n    public static bool operator !=(Integer x, Integer y) { return x.value != y.value; }\n    public override bool Equals(object obj) { return this == (Integer)obj; }\n    public override int GetHashCode() { return this.value.GetHashCode(); }\n    public override string ToString() { return this.value.ToString(); }\n    public static bool operator &gt;(Integer x, Int16 y) { return x.value &gt; y; }\n    public static bool operator &lt;(Integer x, Int16 y) { return x.value &lt; y; }\n    public static bool operator &gt;(Integer x, Int32 y) { return x.value &gt; y; }\n    public static bool operator &lt;(Integer x, Int32 y) { return x.value &lt; y; }\n    public static bool operator &gt;(Integer x, Int64 y) { return x.value &gt; y; }\n    public static bool operator &lt;(Integer x, Int64 y) { return x.value &lt; y; }\n    public static bool operator &gt;(Integer x, UInt16 y) { return x.value &gt; y; }\n    public static bool operator &lt;(Integer x, UInt16 y) { return x.value &lt; y; }\n    public static bool operator &gt;(Integer x, UInt32 y) { return x.value &gt; y; }\n    public static bool operator &lt;(Integer x, UInt32 y) { return x.value &lt; y; }\n    public static bool operator &gt;(Integer x, UInt64 y) { return x.value &gt; y; }\n    public static bool operator &lt;(Integer x, UInt64 y) { return x.value &lt; y; }\n    public static bool operator &gt;(Integer x, Integer y) { return x.value &gt; y.value; }\n    public static bool operator &lt;(Integer x, Integer y) { return x.value &lt; y.value; }\n    public static bool operator &gt;=(Integer x, Int16 y) { return x.value &gt;= y; }\n    public static bool operator &lt;=(Integer x, Int16 y) { return x.value &lt;= y; }\n    public static bool operator &gt;=(Integer x, Int32 y) { return x.value &gt;= y; }\n    public static bool operator &lt;=(Integer x, Int32 y) { return x.value &lt;= y; }\n    public static bool operator &gt;=(Integer x, Int64 y) { return x.value &gt;= y; }\n    public static bool operator &lt;=(Integer x, Int64 y) { return x.value &lt;= y; }\n    public static bool operator &gt;=(Integer x, UInt16 y) { return x.value &gt;= y; }\n    public static bool operator &lt;=(Integer x, UInt16 y) { return x.value &lt;= y; }\n    public static bool operator &gt;=(Integer x, UInt32 y) { return x.value &gt;= y; }\n    public static bool operator &lt;=(Integer x, UInt32 y) { return x.value &lt;= y; }\n    public static bool operator &gt;=(Integer x, UInt64 y) { return x.value &gt;= y; }\n    public static bool operator &lt;=(Integer x, UInt64 y) { return x.value &lt;= y; }\n    public static bool operator &gt;=(Integer x, Integer y) { return x.value &gt;= y.value; }\n    public static bool operator &lt;=(Integer x, Integer y) { return x.value &lt;= y.value; }\n    public static Integer operator +(Int16 x, Integer y) { return new Integer(x + y.value); }\n    public static Integer operator +(Int32 x, Integer y) { return new Integer(x + y.value); }\n    public static Integer operator +(Int64 x, Integer y) { return new Integer(x + y.value); }\n    public static Integer operator +(UInt16 x, Integer y) { return new Integer(x + y.value); }\n    public static Integer operator +(UInt32 x, Integer y) { return new Integer(x + y.value); }\n    public static Integer operator +(UInt64 x, Integer y) { return new Integer(x + y.value); }\n    public static Integer operator -(Int16 x, Integer y) { return new Integer(x - y.value); }\n    public static Integer operator -(Int32 x, Integer y) { return new Integer(x - y.value); }\n    public static Integer operator -(Int64 x, Integer y) { return new Integer(x - y.value); }\n    public static Integer operator -(UInt16 x, Integer y) { return new Integer(x - y.value); }\n    public static Integer operator -(UInt32 x, Integer y) { return new Integer(x - y.value); }\n    public static Integer operator -(UInt64 x, Integer y) { return new Integer(x - y.value); }\n    public static Integer operator *(Int16 x, Integer y) { return new Integer(x * y.value); }\n    public static Integer operator *(Int32 x, Integer y) { return new Integer(x * y.value); }\n    public static Integer operator *(Int64 x, Integer y) { return new Integer(x * y.value); }\n    public static Integer operator *(UInt16 x, Integer y) { return new Integer(x * y.value); }\n    public static Integer operator *(UInt32 x, Integer y) { return new Integer(x * y.value); }\n    public static Integer operator *(UInt64 x, Integer y) { return new Integer(x * y.value); }\n    public static Integer operator /(Int16 x, Integer y) { return new Integer(x / y.value); }\n    public static Integer operator /(Int32 x, Integer y) { return new Integer(x / y.value); }\n    public static Integer operator /(Int64 x, Integer y) { return new Integer(x / y.value); }\n    public static Integer operator /(UInt16 x, Integer y) { return new Integer(x / y.value); }\n    public static Integer operator /(UInt32 x, Integer y) { return new Integer(x / y.value); }\n    public static Integer operator /(UInt64 x, Integer y) { return new Integer(x / y.value); }\n    public static Integer operator %(Int16 x, Integer y) { return new Integer(x % y.value); }\n    public static Integer operator %(Int32 x, Integer y) { return new Integer(x % y.value); }\n    public static Integer operator %(Int64 x, Integer y) { return new Integer(x % y.value); }\n    public static Integer operator %(UInt16 x, Integer y) { return new Integer(x % y.value); }\n    public static Integer operator %(UInt32 x, Integer y) { return new Integer(x % y.value); }\n    public static Integer operator %(UInt64 x, Integer y) { return new Integer(x % y.value); }\n    public static bool operator ==(Int16 x, Integer y) { return x == y.value; }\n    public static bool operator !=(Int16 x, Integer y) { return x != y.value; }\n    public static bool operator ==(Int32 x, Integer y) { return x == y.value; }\n    public static bool operator !=(Int32 x, Integer y) { return x != y.value; }\n    public static bool operator ==(Int64 x, Integer y) { return x == y.value; }\n    public static bool operator !=(Int64 x, Integer y) { return x != y.value; }\n    public static bool operator ==(UInt16 x, Integer y) { return x == y.value; }\n    public static bool operator !=(UInt16 x, Integer y) { return x != y.value; }\n    public static bool operator ==(UInt32 x, Integer y) { return x == y.value; }\n    public static bool operator !=(UInt32 x, Integer y) { return x != y.value; }\n    public static bool operator ==(UInt64 x, Integer y) { return x == y.value; }\n    public static bool operator !=(UInt64 x, Integer y) { return x != y.value; }\n    public static bool operator &gt;(Int16 x, Integer y) { return x &gt; y.value; }\n    public static bool operator &lt;(Int16 x, Integer y) { return x &lt; y.value; }\n    public static bool operator &gt;(Int32 x, Integer y) { return x &gt; y.value; }\n    public static bool operator &lt;(Int32 x, Integer y) { return x &lt; y.value; }\n    public static bool operator &gt;(Int64 x, Integer y) { return x &gt; y.value; }\n    public static bool operator &lt;(Int64 x, Integer y) { return x &lt; y.value; }\n    public static bool operator &gt;(UInt16 x, Integer y) { return x &gt; y.value; }\n    public static bool operator &lt;(UInt16 x, Integer y) { return x &lt; y.value; }\n    public static bool operator &gt;(UInt32 x, Integer y) { return x &gt; y.value; }\n    public static bool operator &lt;(UInt32 x, Integer y) { return x &lt; y.value; }\n    public static bool operator &gt;(UInt64 x, Integer y) { return x &gt; y.value; }\n    public static bool operator &lt;(UInt64 x, Integer y) { return x &lt; y.value; }\n    public static bool operator &gt;=(Int16 x, Integer y) { return x &gt;= y.value; }\n    public static bool operator &lt;=(Int16 x, Integer y) { return x &lt;= y.value; }\n    public static bool operator &gt;=(Int32 x, Integer y) { return x &gt;= y.value; }\n    public static bool operator &lt;=(Int32 x, Integer y) { return x &lt;= y.value; }\n    public static bool operator &gt;=(Int64 x, Integer y) { return x &gt;= y.value; }\n    public static bool operator &lt;=(Int64 x, Integer y) { return x &lt;= y.value; }\n    public static bool operator &gt;=(UInt16 x, Integer y) { return x &gt;= y.value; }\n    public static bool operator &lt;=(UInt16 x, Integer y) { return x &lt;= y.value; }\n    public static bool operator &gt;=(UInt32 x, Integer y) { return x &gt;= y.value; }\n    public static bool operator &lt;=(UInt32 x, Integer y) { return x &lt;= y.value; }\n    public static bool operator &gt;=(UInt64 x, Integer y) { return x &gt;= y.value; }\n    public static bool operator &lt;=(UInt64 x, Integer y) { return x &lt;= y.value; }\n}\npublic static class Program\n{\n    private static bool IntegerFunction(Integer n)\n    {\n        //code that implements IntegerFunction goes here\n        //note that there is NO code that checks the type of n in rum time, because it is NOT needed anymore \n    }\n    private static void Main()\n    {\n        Console.WriteLine("{0}",IntegerFunction(0)); //compile error: there is no overloaded METHOD for objects of type "int" and no implicit conversion from any object, including "int", to "Integer" is known.\n        Console.WriteLine("{0}",IntegerFunction(new Integer(0))); //both compiles and no run time error\n        Console.WriteLine("{0}",IntegerFunction("string")); //compile error: there is no overloaded METHOD for objects of type "string" and no implicit conversion from any object, including "string", to "Integer" is known.\n        Console.WriteLine("{0}",IntegerFunction(new Integer("string"))); //compile error: there is no overloaded CONSTRUCTOR for objects of type "string"\n    }\n}\n</code></pre>\n\n<p>Note that in order to use <strong>dynamic</strong> in your code you must <strong>Add Reference</strong> to <strong>Microsoft.CSharp</strong></p>\n\n<p>If the version of the .NET framework is below/under/lesser than 4.0 and <strong>dynamic</strong> is undefined in that version then you will have to use <strong>object</strong> instead and do casting to the integer type, which is trouble, so I recommend that you use at least .NET 4.0 or newer if you can so you can use <strong>dynamic</strong> instead of <strong>object</strong>.</p>\n'}, {'answer_id': 53663980, 'author': 'user276648', 'author_id': 276648, 'author_profile': 'https://Stackoverflow.com/users/276648', 'pm_score': 0, 'selected': False, 'text': "<p>If all you want is use <strong>one numeric type</strong>, you could consider creating something similar to an alias in C++ with <code>using</code>.</p>\n\n<p>So instead of having the very generic</p>\n\n<pre><code>T ComputeSomething&lt;T&gt;(T value1, T value2) where T : INumeric { ... }\n</code></pre>\n\n<p>you could have</p>\n\n<pre><code>using MyNumType = System.Double;\nT ComputeSomething&lt;MyNumType&gt;(MyNumType value1, MyNumType value2) { ... }\n</code></pre>\n\n<p>That might allow you to easily go from <code>double</code> to <code>int</code> or others if needed, but you wouldn't be able to use <code>ComputeSomething</code> with <code>double</code> and <code>int</code> in the same program.</p>\n\n<p>But why not replace all <code>double</code> to <code>int</code> then? Because your method may want to use a <code>double</code> whether the input is <code>double</code> or <code>int</code>. The alias allows you to know exactly which variable uses the <em>dynamic</em> type.</p>\n"}, {'answer_id': 53703357, 'author': 'DrGriff', 'author_id': 584714, 'author_profile': 'https://Stackoverflow.com/users/584714', 'pm_score': 2, 'selected': False, 'text': "<p>I had a similar situation where I needed to handle numeric types and strings; seems a bit of a bizarre mix but there you go.</p>\n\n<p>Again, like many people I looked at constraints and came up with a bunch of interfaces that it had to support.  However, a) it wasn't 100% watertight and b), anyone new looking at this long list of constraints would be immediately very confused.</p>\n\n<p>So, my approach was to put all my logic into a generic method with no constraints, but to make that generic method private.  I then exposed it with public methods, one explicitly handling the type I wanted to handle - to my mind, the code is clean and explicit, e.g.</p>\n\n<pre><code>public static string DoSomething(this int input, ...) =&gt; DoSomethingHelper(input, ...);\npublic static string DoSomething(this decimal input, ...) =&gt; DoSomethingHelper(input, ...);\npublic static string DoSomething(this double input, ...) =&gt; DoSomethingHelper(input, ...);\npublic static string DoSomething(this string input, ...) =&gt; DoSomethingHelper(input, ...);\n\nprivate static string DoSomethingHelper&lt;T&gt;(this T input, ....)\n{\n    // complex logic\n}\n</code></pre>\n"}, {'answer_id': 59991325, 'author': 'TylerBrinkley', 'author_id': 8137269, 'author_profile': 'https://Stackoverflow.com/users/8137269', 'pm_score': 2, 'selected': False, 'text': '<p>Unfortunately .NET doesn\'t provide a way to do that natively.</p>\n\n<p>To address this issue I created the OSS library <a href="https://github.com/TylerBrinkley/Genumerics" rel="nofollow noreferrer">Genumerics</a> which provides most standard numeric operations for the following built-in numeric types and their nullable equivalents with the ability to add support for other numeric types.</p>\n\n<p><code>sbyte</code>, <code>byte</code>, <code>short</code>, <code>ushort</code>, <code>int</code>, <code>uint</code>, <code>long</code>, <code>ulong</code>, <code>float</code>, <code>double</code>, <code>decimal</code>, and <code>BigInteger</code></p>\n\n<p>The performance is equivalent to a numeric type specific solution allowing you to create efficient generic numeric algorithms.</p>\n\n<p>Here\'s an example of the code usage.</p>\n\n<pre class="lang-cs prettyprint-override"><code>public static T Sum(T[] items)\n{\n    T sum = Number.Zero&lt;T&gt;();\n    foreach (T item in items)\n    {\n        sum = Number.Add(sum, item);\n    }\n    return sum;\n}\n</code></pre>\n\n<pre class="lang-cs prettyprint-override"><code>public static T SumAlt(T[] items)\n{\n    // implicit conversion to Number&lt;T&gt;\n    Number&lt;T&gt; sum = Number.Zero&lt;T&gt;();\n    foreach (T item in items)\n    {\n        // operator support\n        sum += item;\n    }\n    // implicit conversion to T\n    return sum;\n}\n</code></pre>\n'}, {'answer_id': 60022011, 'author': 'Vlad', 'author_id': 1544015, 'author_profile': 'https://Stackoverflow.com/users/1544015', 'pm_score': 5, 'selected': False, 'text': '<p>Beginning with C# 7.3, you can use closer <strong>approximation</strong> - the <strong>unmanaged constraint</strong> to specify that a type parameter is a non-pointer, non-nullable <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/unmanaged-types" rel="noreferrer">unmanaged</a> type.</p>\n<pre><code>class SomeGeneric&lt;T&gt; where T : unmanaged\n{\n//...\n}\n</code></pre>\n<p>The unmanaged constraint implies the struct constraint and can\'t be combined with either the struct or new() constraints.</p>\n<p>A type is an unmanaged type if it\'s any of the following types:</p>\n<ul>\n<li>sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool</li>\n<li>Any enum type</li>\n<li>Any pointer type</li>\n<li>Any user-defined struct type that contains fields of unmanaged types only and, in C# 7.3 and earlier, is not a constructed type (a type that includes at least one type argument)</li>\n</ul>\n<p>To restrict further and eliminate pointer and user-defined types that do not implement IComparable add <strong>IComparable</strong> (but enum is still derived from IComparable, so restrict enum by adding IEquatable &lt; T &gt;, you can go further depending on your circumstances and add additional interfaces. unmanaged allows to keep this list shorter):</p>\n<pre><code>    class SomeGeneric&lt;T&gt; where T : unmanaged, IComparable, IEquatable&lt;T&gt;\n    {\n    //...\n    }\n</code></pre>\n<p>But this doesn\'t prevent from DateTime instantiation.</p>\n'}, {'answer_id': 62211277, 'author': 'Arman Ebrahimpour', 'author_id': 9212040, 'author_profile': 'https://Stackoverflow.com/users/9212040', 'pm_score': 4, 'selected': False, 'text': '<p>Topic is old but for future readers:</p>\n\n<p>This feature is tightly related to <code>Discriminated Unions</code> which is not implemented in C# so far. I found its issue here:</p>\n\n<p><a href="https://github.com/dotnet/csharplang/issues/113" rel="noreferrer">https://github.com/dotnet/csharplang/issues/113</a></p>\n\n<p>This issue is still open and feature has been planned for <code>C# 10</code></p>\n\n<p>So still we have to wait a bit more, but after releasing you can do it this way:</p>\n\n<pre><code>static bool IntegerFunction&lt;T&gt;(T value) where T : Int16 | Int32 | Int64 | ...\n</code></pre>\n'}, {'answer_id': 68753665, 'author': 'Dan', 'author_id': 4601149, 'author_profile': 'https://Stackoverflow.com/users/4601149', 'pm_score': 5, 'selected': True, 'text': '<p>This constraint exists in .Net 7.</p>\n<p>Check out this <a href="https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/" rel="nofollow noreferrer">.NET Blog post</a> and the <a href="https://learn.microsoft.com/en-us/dotnet/standard/generics/math" rel="nofollow noreferrer">actual documentation</a>.</p>\n<p>Starting in .NET 7, you can make use of interfaces such as <code>INumber</code> and <code>IFloatingPoint</code> to create programs such as:</p>\n<pre><code>using System.Numerics;\n\nConsole.WriteLine(Sum(1, 2, 3, 4, 5));\nConsole.WriteLine(Sum(10.541, 2.645));\nConsole.WriteLine(Sum(1.55f, 5, 9.41f, 7));\n\nstatic T Sum&lt;T&gt;(params T[] numbers) where T : INumber&lt;T&gt;\n{\n    T result = T.Zero;\n\n    foreach (T item in numbers)\n    {\n        result += item;\n    }\n\n    return result;\n}\n</code></pre>\n<p><code>INumber</code> is in the <code>System.Numerics</code> namespace.</p>\n<p>There are also interfaces such as <code>IAdditionOperators</code> and <code>IComparisonOperators</code> so you can make use of specific operators generically.</p>\n'}, {'answer_id': 69288660, 'author': 'lonix', 'author_id': 9971404, 'author_profile': 'https://Stackoverflow.com/users/9971404', 'pm_score': 0, 'selected': False, 'text': '<p>All numeric types <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#value-types" rel="nofollow noreferrer">are structs</a> which implement <code>IComparable, IComparable&lt;T&gt;, IConvertible, IEquatable&lt;T&gt;, IFormattable</code>. However, so does <code>DateTime</code>.</p>\n<p>So this generic extension method is possible:</p>\n<pre class="lang-cs prettyprint-override"><code>public static bool IsNumeric&lt;T&gt;(this T value) where T : struct, IComparable, IComparable&lt;T&gt;, IConvertible, IEquatable&lt;T&gt;, IFormattable =&gt;\n  typeof(T) != typeof(DateTime);\n</code></pre>\n<p>But it will fail for a struct that implements those interfaces, e.g.:</p>\n<pre class="lang-cs prettyprint-override"><code>public struct Foo : IComparable, IComparable&lt;Foo&gt;, IConvertible, IEquatable&lt;Foo&gt;, IFormattable { /* ... */ }\n</code></pre>\n<p>This non-generic alternative is less performant, but guaranteed to work:</p>\n<pre class="lang-cs prettyprint-override"><code>public static bool IsNumeric(this Type type) =&gt;\n  type == typeof(sbyte) || type == typeof(byte) ||\n  type == typeof(short) || type == typeof(ushort) ||\n  type == typeof(int) || type == typeof(uint) ||\n  type == typeof(long) || type == typeof(ulong) ||\n  type == typeof(float) ||\n  type == typeof(double) ||\n  type == typeof(decimal);\n</code></pre>\n'}, {'answer_id': 70046713, 'author': 'asaf92', 'author_id': 6104191, 'author_profile': 'https://Stackoverflow.com/users/6104191', 'pm_score': 2, 'selected': False, 'text': '<p>.NET 6 has this functionality a preview feature:</p>\n<p><a href="https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/#generic-math" rel="nofollow noreferrer">https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/#generic-math</a></p>\n<p>An example from the article:</p>\n<pre><code>static T Add&lt;T&gt;(T left, T right)\n    where T : INumber&lt;T&gt;\n{\n    return left + right;\n}\n</code></pre>\n<p><code>INumber</code> is an interface that implements other interfaces, such as <code>IAdditionOperators</code> which allows the generic <code>+</code> usage. This is possible now because of another preview feature which is the static abstracts in interfaces, because the <code>+</code> operator overload is a static method:</p>\n<pre><code>/// &lt;summary&gt;Defines a mechanism for computing the sum of two values.&lt;/summary&gt;\n/// &lt;typeparam name=&quot;TSelf&quot;&gt;The type that implements this interface.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;TOther&quot;&gt;The type that will be added to &lt;typeparamref name=&quot;TSelf&quot; /&gt;.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;TResult&quot;&gt;The type that contains the sum of &lt;typeparamref name=&quot;TSelf&quot; /&gt; and &lt;typeparamref name=&quot;TOther&quot; /&gt;.&lt;/typeparam&gt;\n[RequiresPreviewFeatures(Number.PreviewFeatureMessage, Url = Number.PreviewFeatureUrl)]\npublic interface IAdditionOperators&lt;TSelf, TOther, TResult&gt;\n    where TSelf : IAdditionOperators&lt;TSelf, TOther, TResult&gt;\n{\n    /// &lt;summary&gt;Adds two values together to compute their sum.&lt;/summary&gt;\n    /// &lt;param name=&quot;left&quot;&gt;The value to which &lt;paramref name=&quot;right&quot; /&gt; is added.&lt;/param&gt;\n    /// &lt;param name=&quot;right&quot;&gt;The value which is added to &lt;paramref name=&quot;left&quot; /&gt;.&lt;/param&gt;\n    /// &lt;returns&gt;The sum of &lt;paramref name=&quot;left&quot; /&gt; and &lt;paramref name=&quot;right&quot; /&gt;.&lt;/returns&gt;\n    static abstract TResult operator +(TSelf left, TOther right);\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/32664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1736/']