C# Error CS0145 – A const field requires a value to be provided

C# Compiler Error

CS0145 – A const field requires a value to be provided

Reason for the Error

When declaring a constant, you will have to initialize the constant variable with the value. When you don’t initialize the constant variable, you’ll receive this error.

For example, the below C# code snippet will result with the C# compiler error CS0145 as the constant field Id is not initialized.

namespace DeveloperPublishNamespace
{
    public class DeveloperPublish
    {
        const int Id;
        public static void Main()
        {
           
        }
    }

}

Error CS0145 A const field requires a value to be provided ConsoleApp1 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp1\Program.cs 5 Active

C# Error CS0145 – A const field requires a value to be provided

Solution

When declaring the constant variable, ensure that you initialize it. Alternatively, you can look at using readonly instead of const where you don’t want to initialize the variable.

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