Charles Mark Carroll
Charles Mark Carroll

Reputation: 189

C# Generics for certain kinds of numbers where constraints won't work

I use generics a LOT but narrow cases challenge me...

   public static T RandomNumberImproved <T>(int min, int max)
   {
       bool bolLegit=false;
       if (typeof(T) == typeof(int))
       {
           bolLegit=true;
           return (T) RandomNumberLong(min, max);
       }

       if (typeof(T) == typeof(double))
       {
           bolLegit=true;
           return (T) RandomNumberDouble(min, max);
       }
  if(!bolLegit) throw new Exception("Unsupported Number Format");

   }// end RandomNumberImproved

Of course I get errors can't convert to return type T.

Lots of my generic code works great when I can support n types and when constraints help. Cases like this stump me....

Upvotes: 1

Views: 119

Answers (1)

usr
usr

Reputation: 171188

This is not what generics are made for.

I recommend that you split this method into two methods RandomNumberInt32 and RandomNumberDouble.

There is a way to make this work however:

return (T)(object)RandomNumberLong(min, max);

But it has nasty performance and is counter-intuitive. I would vastly prefer the specialized methods alternative.

I do not understand why this question was downvoted.

Upvotes: 1

Related Questions