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

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