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

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...