astidham2003
astidham2003

Reputation: 964

Why does C# is keyword return true for double, but false for float even though casting to float works?

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();
    }
}

Upvotes: 4

Views: 296

Answers (3)

Riad Baghbanli
Riad Baghbanli

Reputation: 3319

You explicitly casting double value to float variable. It is perfectly fine. When you checking the type, it is exact type match. What you need is:

if (value is double || value is float)
{
    myVariable = (float)value;
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502786

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.

Upvotes: 4

Linus Caldwell
Linus Caldwell

Reputation: 11068

Not sure, but I guess it is because there is no implicit conversion. See Implicit Numeric Conversions Table (C# Reference)

Upvotes: 0

Related Questions