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

C# Error CS0039 – Cannot convert type ‘type1’ to ‘type2’ via a reference conversion, boxing conversion

C# Compiler Error Message

Cannot convert type ‘type1’ to ‘type2’ via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

Reason for the Error

You will receive the error CS0039 when you are trying to convert or perform typecasting using the as reference and there is no direct inheritence between the classes.

For example, try compiling this code.

class classA { }
class classB : classA { }
class classC : classA { }

class DeveloperPublishMain
{
    static void Main()
    {
        classC c;

        classA a = new classC();
        c = a as classC;

        classB b = new classB();
        c = b as classC;  
    }
}

You will receive the below error

Error CS0039 Cannot convert type ‘classB’ to ‘classC’ via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

You will receive the error because classC is not the parent or doesnot have any direct inheritance with classB.

C# Error CS0039 – Cannot convert type 'type1' to 'type2' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

Solution

A conversion with the as operator is only allowed by inheritance, reference conversions, and boxing conversions. You will need to remove the necessary type casting or change the logic of how you are converting.