Motivation: I have a method that returns a dynamic datatype. The value is coming from a database and I know that the value will either be a float, double, or string. I don't 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 type of value was double or float because of the following snippet from the documentation of the 'is' keyword:
An is expression evaluates to true if the provided expression is non-null,and the provided object can be cast to the provided type without causing an exception to be thrown.
Found here: is (C# Reference)
However, when the type is double, (value is float) returns false and the assignment does not execute. But, I changed my code to this:
if (value is double)
{
myVariable = (float)value;
}
and it works fine when the type of value is double - even though according to the documentation I shouldn't be able to cast to a float because (value is float) returns false.
My Question: Why does (value is float) return false in the case where value is a double (which can be cast to a float without exception)?
EDIT - 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();
}
}
Right, this is because the type is dynamic
. That basically means the meaning of the float
cast depends on the execution-time type of the value.
The is
operator is checking whether float
and double
are the same type - and they're not, which is why it's returning false.
However, there is an explicit conversion from double
to float
, which is why the cast is working. I wouldn't use that MSDN C# reference to work out the finer details of how the language behaves - the language specification is normally a better bet.
See more on this question at Stackoverflow