C# Error CS0221 – Constant value ‘value’ cannot be converted to a ‘type’ (use ‘unchecked’ syntax to override)

C# Compiler Error

CS0221 – Constant value ‘value’ cannot be converted to a ‘type’ (use ‘unchecked’ syntax to override)

Reason for the Error

You will receive this error when the C# compiler detects that an assignment operation will result with data loss. This happens because by default checked block is used in .NET.

For example, try to compile the below code snippet.

namespace DeveloperPubNamespace
{   
    class Program
    {
        static void Main()
        {
            int input = (int)9999999999;  

        }
    }
}

This program will result with the error code CS0221 because C# compiler has detected that there is an assignment of a constant value that will result with the overflow value.

Error CS0221 Constant value ‘9999999999’ cannot be converted to a ‘int’ (use ‘unchecked’ syntax to override) ConsoleApp3 C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 8 Active

C# Error CS0221 – Constant value 'value' cannot be converted to a 'type' (use 'unchecked' syntax to override)

Solution

To fix the error code CS0220 in C#, you’ll either need to correct the value that is assigned or use the unchecked block to perform this operation.

namespace DeveloperPubNamespace
{   
    class Program
    {
        static void Main()
        {
            unchecked
            {
                int input = (int)9999999999;
            }

        }
    }

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