I have a method:
public void StoreNumberInSmallestType(ValueType number)
{
if (numberTypes == null)
numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };
foreach (Type t in numberTypes)
{
try
{
var converter = TypeDescriptor.GetConverter(t);
value = converter.ConvertTo(number, t);
Type = value.GetType();
return;
}
catch (OverflowException) { }
}
}
The method is inside a class where the variable value
is defined as dynamic
.
When used like this:
StoreNumberInSmallestType(Math.Pow(200, 100));
value
ends up being Infinity
. If I step through the process, I find that the value of number
is not Infinity
, but is the result expressed in scientific notation. Something bad is happening whenever number
gets converted and stored inside value
. Does anybody know why number
holds the correct value, but value
does not?
Here is a complete code sample:
Main:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Class1 c1 = new Class1();
c1.StoreNumberInSmallestType(Math.Pow(200, 100));
}
}
}
Class:
namespace ConsoleApplication1
{
public class Class1
{
List<Type> numberTypes;
dynamic value;
public Type Type { get; set; }
public void StoreNumberInSmallestType(ValueType number)
{
if (numberTypes == null)
numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };
foreach (Type t in numberTypes)
{
try
{
var converter = TypeDescriptor.GetConverter(t);
value = converter.ConvertTo(number, t);
Type = value.GetType();
return;
}
catch (OverflowException) { }
}
}
}
}
You don't get infinity for the double conversion, but for the float conversion.
There you get Infinity and no exception and then your code returns before you get to the double conversion.