C# Error CS0020 – Division by constant zero

C# Compiler Error Message

CS0020 Division by constant zero

Reason for the Error

You would usually receive this error when you use literal value by zero in the denominator. For example, compile the below C# code.

using System;
public class DeveloperPublish
{
    public static void Main()
    {
        var result = 19 / 0;
        Console.WriteLine(result);
    }
}

You will receive the below error.

Error CS0020 Division by constant zero ConsoleApp1 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp1\Program.cs

Solution

The error is specifically caused when the literal value of 0 is used in the denominator during the division.

When you change the denominator value/dividend to use a variable instead of literal, you could see the compiler error would be stopped, but still would result in the runtime exception.

For example, the below code snippet, although has a value of 0, since it is a variable, you will not receive the compiler error.

using System;
public class DeveloperPublish
{
    public static void Main()
    {
        int denominator = 0;
        var result = 19 / denominator;
        Console.WriteLine(result);
    }
}

You will however receive the below run time error when running the application.

C# Error CS0020 – Division by constant zero

System.DivideByZeroException: ‘Attempted to divide by zero.’

For a better solution, you will need to ensure that you do checks to ensure that the denominator doesnot contain zero has a value before dividing.

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