C# Error CS0031 – Constant value ‘value’ cannot be converted to a ‘type’

C# Compiler Error Message

CS0031 Constant value ‘value’ cannot be converted to a ‘type’

Reason for the Error

You will receive this error when you assign a value to a variable which cannot store the value.

Take an example of the below code snippet

using System;
public class DeveloperPublish
{
    public static void Main()
    {
        const decimal input = -25M; // Decimal literal
        byte output = (byte)input;
    }
}

You have a constant with the name input of type decimal which holds the value -25M. This is assigned to the variable output by typecasting it. This will result with the below error.

There are times when the Compiler might result with the error code CS0266 (example – when using Mono framework) as the conversion from one type to another type will result with the similar error.

Error CS0031 Constant value ‘-25M’ cannot be converted to a ‘byte’ ConsoleApp1 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp1\Program.cs

C# Error CS0031	- Constant value 'value' cannot be converted to a 'type'

Solution

To fix this issue, ensure that you use assign the values to the variable that holds the right data type.

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