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.

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.

You cannot copy content of this page