Export (0) Print
Expand All
Expand Minimize
2 out of 5 rated this helpful - Rate this topic

Compiler Error CS0266

Cannot implicitly convert type 'type1' to 'type2'. An explicit conversion exists (are you missing a cast?)

This error occurs when your code tries to convert between two types that cannot be implicitly converted, but where an explicit conversion is available. For more information, see Casting and Type Conversions (C# Programming Guide).

The following code shows examples that generate CS0266.

// CS0266.cs
class MyClass
{
    public static void Main()
    {
        // You cannot implicitly convert a double to an integer.
        double d = 3.2;

        // The following line causes compiler error CS0266.
        int i1 = d;

        // However, you can resolve the error by using an explicit conversion.
        int i2 = (int)d;


        // You cannot implicitly convert an object to a class type.
        object obj = "MyString";

        // The following assignment statement causes error CS0266.
        MyClass myClass = obj;  

        // You can resolve the error by using an explicit conversion.
        MyClass c = ( MyClass )obj;


        // You cannot implicitly convert a base class object to a derived class type.
        MyClass mc = new MyClass();
        DerivedClass dc = new DerivedClass();

        // The following line causes compiler error CS0266.
        dc = mc;

        // You can resolve the error by using an explicit conversion.
        dc = (DerivedClass)mc;
    }
}

class DerivedClass : MyClass
{
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.