Discover how to solve the 40 most frequent C# compile-time errors with our in-depth guide.
The article demonstrates common compile-time errors from missing semicolons to type mismatches and solutions to fix those compile-time errors.
CS1002: ; expected
happens when a developer misses semicolons (;) at the end of a code line.
int number = 10
Console.WriteLine(number)
The compiler will highlight the line number and a simple solution is to add a semicolon at the end of the statement
int number = 10;
Console.WriteLine(number);
Missing braces ({ or })
can cause a set of errors, including
public class Program
{
public static void Main()
Console.WriteLine("Hello, world!");
}
}
Make sure to close the brace for each opening brace.
public class Program
{
public static void Main()
{
Console.WriteLine("Hello, world!");
}
}
CS0103 The name 'number' does not exist in the current context
happens when a variable that has not been defined or is out of scope.
public class Program
{
public static void Main()
{
Console.WriteLine(number);
}
}
Define the variable as shown below before printing on the console window.
public class Program
{
public static void Main()
{
int number = 10;
Console.WriteLine(number);
}
}
A data type mismatch error, indicated by CS0029 Cannot implicitly convert type ‘string’ to ‘int’
, which usually happens when one data type is assigned a different data type value as shown below.
int number = "123";
Developers need to make sure of the type conversion as shown below using int.Parse for converting a string to an integer variable.
int number = int.Parse("123");
CS1503 Argument 1: cannot convert from 'string' to 'int'
happens when you pass an incorrect type in comparison to the method definition or forget to create/define a method.
public class Program
{
public static void PrintNumber(int num)
{
Console.WriteLine(num);
}
public static void Main()
{
PrintNumber("123");
}
}
A simple solution is to match the type of value passed with the function parameter definition or use type conversion.
public class Program
{
public static void PrintNumber(int num)
{
Console.WriteLine(num);
}
public static void Main()
{
PrintNumber(int.Parse("123"));
}
}
CS0122 'Helper' is inaccessible due to its protection level
happens when a developer provides a type with a higher accessibility level as a method parameter or return type than the method itself
private class Helper
{
}
public class Program
{
public static Helper GetHelper()
{
return new Helper();
}
}
The simplest solution is to match the access modifier of the class Helper with the method GetHelper().
public class Helper
{
}
public class Program
{
public static Helper GetHelper()
{
return new Helper();
}
}
CS0146 Circular base type dependency involving 'ClassA' and 'ClassB'
happens when two classes are inherited from each other.
public class ClassA : ClassB
{
}
public class ClassB : ClassA
{
}
Reevaluate the design to remove the circular dependency.
public class ClassA
{
}
public class ClassB
{
}
CS0266 Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
happens when an implicit conversion is required between two types.
double number = 34.5;
int value = number;
Explicitly cast the double variable to int.
double number = 34.5;
int value = (int)number;
Using conditional attributes like ([Conditional("DEBUG")]) does not result in any output if the conditional symbol is not defined.
[Conditional("DEBUG")]
public static void Log(string message)
{
Console.WriteLine(message);
}
public static void Main()
{
Log("Starting application.");
}
Add a conditional compilation symbol (DEBUG) is defined or handles the logic accordingly as shown below.
#define DEBUG
using System.Diagnostics;
[Conditional("DEBUG")]
public static void Log(string message)
{
Console.WriteLine(message);
}
public static void Main()
{
Log("Starting application.");
}
CS0165 Use of unassigned local variable value
happens when the developer uses a local variable before a value is assigned to it.
int value;
Console.WriteLine(value);
A simple solution is to assign an initial value of 0 to the integer local variable.
int value = 0;
Console.WriteLine(value);
CS0185 'int' is not a reference type as required by the lock statement
that happens when a developer tries to use a lock on the non-reference type.
public void LockMethod() {
int x = 0;
lock (x) { // Error
Console.WriteLine("Locked");
}
}
A simple solution is to make the variable reference type.
public void LockMethod() {
object lockObj = new object();
lock (lockObj) {
Console.WriteLine("Locked");
}
}
CS0144 Cannot create an instance of the abstract type or interface 'Animal '
that happens when a developer tries to create an instance of an abstract class.
public abstract class Animal
{
public abstract void Speak();
}
public class Program
{
public static void Main()
{
Animal myAnimal = new Animal(); // Error
}
}
A simple solution is to create an instance of a class derived from the abstract class as shown below.
public abstract class Animal
{
public abstract void Speak();
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Bark");
}
}
public class Program
{
public static void Main()
{
Animal myAnimal = new Dog();
myAnimal.Speak();
}
}
CS0200 Property or indexer 'Person.Name' cannot be assigned to -- it is read only
happens when you try to use a property’s getter or setter when it’s not defined.
public class Person
{
public string Name { get; }
}
public class Program
{
public static void Main()
{
var person = new Person();
person.Name = "John"; // Error
}
}
A simple solution is to a setter to the property as shown below if required to update the Name value.
public class Person
{
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
var person = new Person();
person.Name = "John";
}
}
CS0535 'Dog' does not implement interface member 'IAnimal.Speak()'
happens when the developer fails to implement the member functions in the derived class.
public interface IAnimal
{
void Speak();
}
public class Dog : IAnimal
{
}
A simple solution is to implement all member functions of the interface as shown below.
public interface IAnimal
{
void Speak();
}
public class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("Bark");
}
}
CS0592 Attribute 'Serializable' is not valid on this declaration type. It is only valid on 'class, struct, enum, delegate' declarations
happens when a developer tries to apply attributes to member functions.
[Serializable]
public int MyMethod() { // Error: Serializable is not valid on methods
return 0;
}
A simple solution is to apply attributes appropriate to program elements.
[Serializable]
public class MyClass { // Correct usage
}
CS0535 'FileStorage' does not implement interface member 'IStorage.Load()'
happens when a method of interface is missing its implementation.
interface IStorage
{
void Save(string data);
string Load();
}
class FileStorage : IStorage
{
public void Save(string data)
{
// Implementation here
}
}
A simple solution is to implement all members defined in the interface.
class FileStorage : IStorage
{
public void Save(string data)
{
// Implementation here
}
public string Load()
{
// Implementation here
return "data";
}
}
CS0176 Member 'Utility.Number' cannot be accessed with an instance reference; qualify it with a type name instead
happens when a developer tries to access a static variable by creating an instance of that class.
public class Utility
{
public static int Number = 42;
}
public class Test
{
public void Display()
{
Utility util = new Utility();
Console.WriteLine(util.Number); // Error
}
}
A simple solution is to access the static members using the class name as shown below.
Console.WriteLine(Utility.Number);
CS0710 Static classes cannot have instance constructors
when the developer tries to create a constructor in a static class.
public static class ApplicationSettings
{
public ApplicationSettings() // Error
{
}
}
A simple solution is to remove the constructor or add a static constructor.
public static class ApplicationSettings
{
// Correct the design or remove the constructor
}
CS0111 Type 'Calculator' already defines a member called 'Add' with the same parameter types
when a developer tries to overload the method with different return types which is not possible.
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public double Add(int a, int b) // Error
{
return a + b;
}
}
A simple solution is to overload methods based upon as shown below by changing the 2nd method parameter type from int to double
public double AddDoubles(double a, double b)
{
return a + b;
}
CS0509 'DerivedClass': cannot derive from sealed type 'BaseClass'
when a developer tries to inherit from a sealed class.
public sealed class BaseClass
{
}
public class DerivedClass : BaseClass // Error
{
}
A simple solution is to remove the sealed keyword if inheritance should be allowed.
public class BaseClass
{
}
public class DerivedClass : BaseClass
{
}
CS0305 Using the generic type 'GenericClass<T>' requires 1 type arguments
when a developer tries to create an object of Generic Class without specifying the T type
public class GenericClass<T> {
}
GenericClass obj = new GenericClass(); // Error
A simple solution is to define the type T as shown below.
GenericClass<int> obj = new GenericClass<int>();
CS0102 The type 'Person' already contains a definition for 'age'
happens when a developer tries to create two different variables within the same name in the same class.
public class Person
{
int age;
string age; // Error
}
A simple solution is to have distinct meaningful names for different variables.
public class Person
{
int age;
string name;
}
CS0191 A read-only field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer)
happens when a developer tries to modify the read-only variable.
public class Settings
{
readonly int maxUsers = 100;
public void SetMaxUsers(int num)
{
maxUsers = num; // Error
}
}
A simple solution is to remove read-only if a value update is required post-constructor initialization.
public class Settings
{
int maxUsers = 100;
public void SetMaxUsers(int num)
{
maxUsers = num;
}
}
CS0022 Wrong number of indices inside []; expected 2
happens when a developer tries to access a 2D matrix without specifying the 2nd indices.
int[,] matrix = new int[3, 2];
int num = matrix[0]; // Error
A simple solution is to provide both of the indices.
int num = matrix[0, 1];
CS0266 Cannot implicitly convert type ‘int’ to ‘StatusCode’. An explicit conversion exists (are you missing a cast?)
enum StatusCode { Ok, Error }
StatusCode code = 1; // Error
A simple solution to add type casting from int to Enum.
StatusCode code = (StatusCode)1;
CS0031 Constant value '256' cannot be converted to a 'byte'
happens when a developer tries to define value outside the type range bound.
enum SmallRange : byte { Min = 0, Max = 256 } // Error: 256 is out of byte range
A simple solution is to change the type for a higher range or adjust the max according to the provided type.
enum SmallRange : ushort { Min = 0, Max = 256 }
CS1003: Syntax error, ',' expected happens when a developer forgets to add a comma (,) between Enum values/
enum Colors { Red Blue, Green } // Error
A simple solution is to organize enum values comma-separated as shown below.
enum Colors { Red, Blue, Green }
CS0236 A field initializer cannot reference the non-static field, method, or property ‘MyStruct.y’
when a developer messes the order variable declaration and tries to assign a value to a variable x but its value is dependent on y
struct MyStruct {
int x = y + 1;
int y = 1; // Error
}
A simple solution is to make an order of variable declaration correct for dependent variables.
struct MyStruct {
int x, y;
MyStruct() {
y = 1;
x = y + 1;
}
}
CS0501 'MyClass.MyMethod()' must declare a body because it is not marked abstract, extern, or partial
when a developer tries to create a non-abstract method without a body.
public class MyClass {
public void MyMethod(); // Error
}
A simple solution is to provide a method implementation or declare a method as abstract as an abstract method doesn’t require any implementation.
public class MyClass {
public void MyMethod() {}
}
CS0506 'Derived.DoWork()': cannot override inherited member 'Base.DoWork()' because it is not marked virtual, abstract, or override
when a developer tries to override a method that is not marked as virtual in the base class.
public class Base {
public void DoWork() {}
}
public class Derived : Base {
public override void DoWork() {} // Error
}
A simple solution is to mark the method as virtual.
public class Base {
public virtual void DoWork() {}
}
Using a nullable type in a switch statement without handling the null case can lead to runtime issues, although it’s a logical error more than a compile-time error.
int? num = null;
switch (num) {
case 1:
Console.WriteLine("One");
break;
// No case for null
}
A simple solution is to handle null in the switch statements involving nullable types.
switch (num) {
case 1:
Console.WriteLine("One");
break;
case null:
Console.WriteLine("No number");
break;
}
CS0311 The type ‘MyClass’ cannot be used as type parameter ‘T’ in the generic type or method ‘MyGenericClass<T>’. There is no implicit reference conversion from ‘MyClass’ to ‘IMyInterface’.
public interface IMyInterface {}
public class MyGenericClass<T> where T : IMyInterface {}
public class MyClass {}
MyGenericClass<MyClass> myClass = new MyGenericClass<MyClass>(); // Error
A simple solution is to make sure that type arguments satisfy the generic constraints.
public class MyClass : IMyInterface {}
MyGenericClass<MyClass> myClass = new MyGenericClass<MyClass>();
CS1526 A new expression requires an argument list or (), [], or {} after type
happens a developer forgot to define a type with new the keyword as with var datatype we need to define a type on the right-hand side.
var x = new; // Error
A simple solution is to define the type as shown below.
var x = new MyClass();
CS0131 The left-hand side of an assignment must be a variable, property or indexer
int i = 0;
i++ = 5;
A simple solution is to assign values only to variables, properties, or indexers.
int i;
i = 5;
CS0161 'GetValue()': not all code paths return a value
when a developer forgets to return a value from a method with a defined return type.
public int GetValue() {
if (DateTime.Now.DayOfWeek == DayOfWeek.Monday) {
return 1;
}
// No return provided for other days
}
A simple solution is to make sure the function returns some value in all conditional statement checks or returns a common response as shown below.
public int GetValue() {
if (DateTime.Now.DayOfWeek == DayOfWeek.Monday) {
return 1;
}
return 0; // Default return value
}
CS0029 Cannot implicitly convert type 'string' to 'int '
when a developer tries to add inconsistent value into an array than its defined type.
int[] array = { 1, "two", 3 }; // Error
A simple solution is to add only int elements in the aforementioned array.
int[] array = { 1, 2, 3 };
CS1998: This async method lacks 'await' operators and will run synchronously
happens when a developer creates an async method without an await the operator will result in a warning.
public async Task ProcessData() {
Console.WriteLine("Processing data");
}
A simple solution is to define a least one await statement otherwise the method will run synchronously.
public async Task ProcessData() {
await Task.Delay(1000); // Simulate asynchronous operation
Console.WriteLine("Processing data");
}
CS0029 Cannot implicitly convert type 'string' to 'int '
when a developer tries to define a case with an invalid type.
int x = 10;
switch (x) {
case "ten": // Error
break;
}
A simple solution is to match the case statement type with the switch expression type.
switch (x) {
case 10:
break;
}
CS0516 Constructor 'MyClass.MyClass()' cannot call itself
when a developer tries to call the constructor within the same class using this.
public class MyClass {
public MyClass() : this() { // Error
}
}
```=
### Solution
A simple solution is to remove the circular constructor call.
```csharp
public class MyClass {
public MyClass() {
// Proper initialization code
}
}
CS0145 A const field requires a value to be provided
when a developer tries to create a constant variable without assigning an initial value.
public class MyClass {
public const string MyConstant; // Error: A constant must have a value
}
A simple solution is to remove the circular constructor call.
public class MyClass {
public const string MyConstant = "Hello World"; // Correctly initialized
}
Thank you for being a part of the C# community! Before you leave:
Follow us: Youtube | X | LinkedIn | Dev.to Visit our other platforms: GitHub