C# "CS0120: an object reference is required for the non-static member" in CI
CS0120 means code in a static context (a static method, Main, or a static field initializer) tries to use an instance member without an instance. The member needs a this, but there is none available.
What this error means
The build fails with CS0120 naming the non-static member. It reproduces deterministically.
dotnet
Program.cs(12,9): error CS0120: An object reference is required for the non-static field,
method, or property 'Calculator.Add(int, int)'Common causes
A static method calls an instance member
Main or another static method invokes an instance method/property without creating an instance first.
A member should have been static
A helper that takes no instance state was written as an instance member but is used from static code.
How to fix it
Provide an instance or make the member static
- Create an instance and call the member on it, or
- Mark the member
staticif it does not use instance state. - Rebuild.
C#
var calc = new Calculator();
int sum = calc.Add(2, 3);How to prevent it
- Mark stateless helpers static so call sites are unambiguous.
- Let analyzers suggest
staticfor members that do not touch instance state.
Related guides
C# "CS0201: only assignment, call, increment ... can be used as a statement" in CIFix C# "CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as…
C# "CS0266: cannot implicitly convert type (cast missing)" in CIFix C# "CS0266: Cannot implicitly convert type A to B. An explicit conversion exists (are you missing a cast?…
C# "CS0017: Program has more than one entry point defined" in CIFix C# "CS0017: Program has more than one entry point defined" in CI - two Main methods (or top-level stateme…