Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a generic C# method that can return either double or decimal?
    primarykey
    data
    text
    <p>I have a method like this:</p> <pre><code>private static double ComputePercentage(ushort level, ushort capacity) { double percentage; if(capacity == 1) percentage = 1; // do calculations... return percentage; } </code></pre> <p>Is it possible to make it of a generic type like "type T" where it can return either decimal or double, depending on the type of method expected (or the type put into the function?)</p> <p>I tried something like this and I couldn't get it to work, because I cannot assign a number like "1" to a generic type. I also tried using the "where T :" after <code>ushort capacity)</code> but I still couldn't figure it out. </p> <pre><code>private static T ComputePercentage&lt;T&gt;(ushort level, ushort capacity) { T percentage; if(capacity == 1) percentage = 1; // error here // do calculations... return percentage; } </code></pre> <p>Is this even possible? I wasn't sure, but I thought <a href="https://stackoverflow.com/questions/828807/what-is-the-base-class-for-c-numeric-value-types/828820#828820">this post</a> might suggest that what I'm trying to do is just plain impossible. </p> <hr> <p><strong>EDIT</strong></p> <p>Thanks to all who responded, many good answers. As <a href="https://stackoverflow.com/questions/2925441/how-to-create-a-generic-c-method-that-can-return-either-double-or-decimal/2925554#2925554">Tomas</a> pointed out, this is probably best done in two separate methods. As pointed out by both <a href="https://stackoverflow.com/questions/2925441/how-to-create-a-generic-c-method-that-can-return-either-double-or-decimal/2925470#2925470">TreDubZedd</a> and <a href="https://stackoverflow.com/questions/2925441/how-to-create-a-generic-c-method-that-can-return-either-double-or-decimal/2925592#2925592">TcKs</a>, the best way to get the functionality I would want is to use an implicit conversion that could return either a double or decimal implicitly. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload