C# Error CS0075 – To cast a negative value, you must enclose the value in parentheses

C# Compiler Error

CS0075 – To cast a negative value, you must enclose the value in parentheses

Reason for the Error

This is an interesting error that you will notice when you are casting a negative value. C# requires you to have the value placed in parenthesis when you are casting it from a negative value.

For example, try compiling the below C# code snippet.

enum EmploymentType { }
public class DeveloperPublish
{
    public static void Main()
    {
        EmploymentType employeeType = (EmploymentType) -1;    
        System.Console.WriteLine(employeeType);
    }
}

You will receive usually receive 2 different errors

Error CS0075 To cast a negative value, you must enclose the value in parentheses.
Error CS0119 ‘EmploymentType’ is a type, which is not valid in the given context ConsoleApp1

C# Error CS0075 – To cast a negative value, you must enclose the value in parentheses

This is because the expression (EmploymentType) -1 is not considered to be a cast expression.

Solution

To fix the error CS0075, you will need to ensure that the negative value that you are trying to cast from is placed with-in the parenthesis. The above code snippet can be fixed by updating EmploymentType employeeType = (EmploymentType) -1; to EmploymentType employeeType = (EmploymentType) (-1);

enum EmploymentType { }
public class DeveloperPublish
{
    public static void Main()
    {
        EmploymentType employeeType = (EmploymentType) (-1);    
        System.Console.WriteLine(employeeType);
    }
}

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