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);
    }
}
Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Hey, wait!Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.