Cannot implicitly convert type 'object' to 'bool'

why do I have to cast an object when I assign its value to a variable, but if I used the GetType() function it returns its value. Sorry my English is bad, but I hope you understood what I'm talking about.

class Program
{
    static void Main(string[] args)
    {
        object o = true;
        Console.WriteLine(o.GetType()); //System.Boolean
        bool s = o; //Cannot implicitly convert type 'object' to 'bool'
    }
}
Jon Skeet
people
quotationmark

You need to understand the difference between the compile-time type of a variable, and the execution-time type of its value. The compiler uses the compile-time type to look up members (e.g. methods) and work out what conversions are available. This includes overload resolution, too.

The execution-time type is used for overriding, and GetType() (which is executed at execution-time, of course) returns the execution-time type of a value. For example:

 object x = "hello";
 Console.WriteLine(x.GetType()); // System.String
 Console.WriteLine(x.Length); // Compile-time error

Here the compile-time type of x is object (aka System.Object) which doesn't have a Length property - so you get a compile-time failure, even though at execution time, the value of x will be a reference to a string.

You can use the dynamic type to force binding to occur at execution time instead, using the execution-time type of the variable:

dynamic x = "hello";
Console.WriteLine(x.Length); // Uses String.Length and prints 5
x = new object[10];
Console.WriteLine(x.Length); // Uses Array.Length and prints 10

However, that's usually a last resort in my experience, for situations which really are dynamic (e.g. accessing JSON data where there is no compile-time type).

people

See more on this question at Stackoverflow