C# Error CS0504 – The constant ‘variable’ cannot be marked static

C# Compiler Error

CS0504 – The constant ‘variable’ cannot be marked static

Reason for the Error

You’ll get this error in your C# code when you mark a variable as both static and const.

For example, let’s try to compile the below C# code snippet.

using System;
namespace DeveloperPublishNamespace
{
    class Program
    {
        static const int Counter = 0;
        static void Main(string[] args)
        {
            Console.WriteLine("No Error");
        }

    }
}

You’ll receive the error code CS0504 because the C# compiler has detected that you have declared the variable “Counter” as both static and const.

Error CS0504 The constant ‘Counter’ cannot be marked static DeveloperPublish C:\Users\Senthil\source\repos\ConsoleApp4\ConsoleApp4\Program.cs 6 Active

C# Error CS0504 – The constant 'variable' cannot be marked static

Solution

In the C# programming language, when you declare a variable as const, it is also static in nature. You can fix this error in your C# program by ensuring that you either mark the variable as static or const instead of both. If you have a use case where you don’t want to change the value of the variable, then use const.

using System;
namespace DeveloperPublishNamespace
{
    class Program
    {
        static int Counter = 0;
        static void Main(string[] args)
        {
            Console.WriteLine("No Error");
        }

    }
}

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