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

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