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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...