Motivation: I have a method that returns a dynamic data type. The value comes from the database, and I know that this value will be either float, double, or string. I do not want to use the value if it is a string, so I wrote the following code:
if (value is float)
{
myVariable = (float)value;
}
My expectation was that this code would execute whether the actual value type was double or floating due to the following snippet from the 'is' keyword documentation:
expression evaluates to true if the provided expression is not null and the provided object can be added to the provided type without causing an exception.
Found here: (C # link)
However, when the type is double, (value is float), returns false, and the assignment is not performed. But I changed my code to this:
if (value is double)
{
myVariable = (float)value;
}
and it works fine when the value type is double - even if according to the documentation I can't use for float because (value is float) returns false.
My question is: Why (value is float) returns false when the value is double (which can be passed to float without exception)?
EDIT is a short program demonstrating
class Program
{
static void Main(string[] args)
{
dynamic d = 1.0;
Console.WriteLine(d is double);
Console.WriteLine(d is float);
float f = (float)d;
Console.WriteLine(f);
Console.ReadKey();
}
}
source
share