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
Solution
To fix this issue, ensure that you use assign the values to the variable that holds the right data type.