HomeCSharpC# Error CS0020 – Division by constant zero

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

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