C# Compiler Error
CS0283 – The type ‘type’ cannot be declared const
Reason for the Error
You’ll get this error in your C# code when you are using a const declaration on type that is not supported. In C#, const declaration can only be applied on specified primitive data types, enums and any reference types that is assigned a value of null.
For example, lets try to compile the below code snippet.
using System; namespace DeveloperPublishNamespace { public class Employee { } class Program { const Employee emp = new Employee(); static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
You’ll receive the error code CS0283 because you are declaring a const objext of type “Employee” by creating an instance. Note that this is a reference type and you are declaring it as constant. This will also result in another error code CS0133.
Error CS0283 The type ‘Employee’ cannot be declared const DeveloperPublish C:\Users\Senthil\source\repos\ConsoleApp4\ConsoleApp4\Program.cs 10 Active
You will receive an different error code as shown below depending on the version of C# that you are running.
CS01344 – Main.cs(10,30): error CS0134: A constant “DeveloperPublishNamespace.Program.emp’ of reference type `DeveloperPublishNamespace.Employee’ can only be initialized with null
Solution
You can fix this error in your C# program by simply changing the const to readonly during your declaration.
using System; namespace DeveloperPublishNamespace { public class Employee { } class Program { readonly Employee emp = new Employee(); static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }