Studies show that good grammar leads to more promotions and higher salaries. Write with Grammarly

C# Error CS0266 – Cannot implicitly convert type ‘type1’ to ‘type2’

C# Compiler Error

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

Reason for the Error

You’ll get this error in your C# code when you try to convert between two types which cannot be implicitly converted. One of the simplest example of this error code is when you try to try to use the implicit conversion from double to int which is not allowed in C#.

For example, lets try to compile the below code snippet.

using System;

namespace DeveloperPubNamespace
using System;

namespace DeveloperPubNamespace
{
    class Program
    {
        public static void Main()
        {        
            double input = 3.2;
            // This will result in the C# error code CS0266
            int outPut = input;

            Console.WriteLine(outPut);
        }
    }
}

You’ll receive the error code CS0266 when you try to build the above C# program because you are assigning the double value to an int variable and expecting the C# implicit conversion to take care of the conversion.

Error CS0266 Cannot implicitly convert type ‘double’ to ‘int’. An explicit conversion exists (are you missing a cast?) DeveloperPublish C:\Users\Senthil\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 11 Active

C# Error CS0266 – Cannot implicitly convert type 'type1' to 'type2'

Solution

You can fix this error in your C# program by explicitly converting to the specified type. The above program can be fixed by explicitly converting the double to int.

using System;

namespace DeveloperPubNamespace
{
    class Program
    {
        public static void Main()
        {        
            double input = 3.2;
            // This will result in the C# error code CS0266
            int outPut = (int)input;

            Console.WriteLine(outPut);
        }
    }
}