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

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

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...