I am writing a random-value generator in C#, this generic function should return value of Type Bool, Int64, Int32, Double depending on the Type passed. So, I can pass the System.Type as a method parameter, but how should I define the return type?
For example
GetRandomValueByType(TypeCode.Boolean) <— Returns Boolean
GetRandomValueByType(TypeCode.Double) <— Returns Double
GetRandomValueByType(TypeCode.Int32) <— Returns Int32
And so on and so forth.
Thank you!
—————————EDIT——————————–
This is the code I used:
if (ta.IsPrimitive || Type.GetTypeCode(ta) == TypeCode.String)
{
Random rnd = new Random();
var buffer = new byte[sizeof(Int64)];
rnd.NextBytes(buffer);
switch (Type.GetTypeCode(ta))
{
case TypeCode.Boolean:
oArr[ctr] = (rnd.Next(100) % 2 == 0);
break;
case TypeCode.Byte:
oArr[ctr] = buffer[0];
break;
case TypeCode.SByte:
oArr[ctr] = (sbyte)buffer[0];
break;
case TypeCode.Char:
oArr[ctr] = Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65));
break;
case TypeCode.Decimal:
oArr[ctr] = NextDecimal(rnd);
break;
case TypeCode.Double:
oArr[ctr] = rnd.NextDouble() * rnd.Next(Int32.MaxValue);
break;
case TypeCode.Single:
var buf = new byte[sizeof(Single)];
rnd.NextBytes(buf);
oArr[ctr] = BitConverter.ToSingle(buffer, 0);
break;
case TypeCode.Int32:
oArr[ctr] = rnd.Next(Int32.MinValue, Int32.MaxValue);
break;
case TypeCode.UInt32:
oArr[ctr] = rnd.Next(Int32.MaxValue) + (rnd.Next(100) % 2) * rnd.Next(Int32.MaxValue);
break;
case TypeCode.Int64:
oArr[ctr] = BitConverter.ToInt64(buffer, 0);
break;
case TypeCode.UInt64:
oArr[ctr] = BitConverter.ToUInt64(buffer, 0);
break;
case TypeCode.Int16:
oArr[ctr] = rnd.Next(Int16.MaxValue);
break;
case TypeCode.UInt16:
oArr[ctr] = rnd.Next(Int16.MaxValue) + (rnd.Next(100) % 2) * rnd.Next(Int16.MaxValue);
break;
case TypeCode.String:
oArr[ctr] = RandomString(rnd.Next(100));
break;
default:
oArr[ctr] = 0;
break;
}
}
else
{
oArr[ctr] = getInstance(dllFile, ta.Name);
}
Generics may be handy here – you could do something like:
This would then be called via:
However, this isn’t entirely safe (not that using
System.Typeis either), as you could still pass a type which implementedIConvertiblebut was inappropriate.Given your comment, I would recommend just making separate methods:
If you’re already going to switch on the type, and make specific implementations, this provides a cleaner, safer way to handle it. By having separate methods, you eliminate the possibility of passing an incorrect type, and simplify the API.