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

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