Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# CS0120: An object reference is required for the non-static member

CS0120 means an instance member was used from a static context. Decide whether the member needs state, then make it static or give the caller an object.

~6 min readC#
#csharp#dotnet#cs0120#compiler-errors
Bold white headline reading CS0120 NO RECEIVER with a .NET static crate reaching for an amber missing instance plate on the right.

Introduction & Quick Summary

The compiler refuses a call that looks perfectly ordinary:

code
Program.cs(12,9): error CS0120: An object reference is required for the non-static field, method, or property 'Greeter.Name'

Quick answer: the member belongs to an instance, and the code that calls it belongs to the class rather than to an object.

csharp
public class Greeter { public string Name { get; set; } = "world"; // instance member public string Hello() => $"Hello, {Name}"; public static void Main() { var g = new Greeter(); // create the instance Console.WriteLine(g.Hello()); } }

CS0120 means the compiler resolved the name to an instance member but the current context has no this. Main is static, so it has no instance; a static field initializer, a static method, a static class and a top-level statement all share that property. The error names the member and, in modern Roslyn output, the exact line and column, which is enough to answer the only question that matters: should this member be static, or should the caller own an object?

Core Mechanics, Signatures & Reproducible Setup

The C# language has exactly two kinds of members: instance members, reachable only through an object, and static members, reachable through the type. A static context has no implicit receiver, so any unqualified reference to an instance member has nothing to attach to.

Reproduce it in a console app:

csharp
namespace Demo; public class Counter { private int count; // instance field public void Increment() => count++; // instance method public static void Reset() => count = 0; // CS0120 on count }

dotnet build reports one error per member, which is why a first build after adding static to a method can produce a wall of them. The related codes are worth knowing because they point in the opposite direction:

CodeMessageMeaning
CS0120An object reference is required for the non-static memberinstance member used in a static context
CS0176Member cannot be accessed with an instance referencestatic member used through an object
CS0236A field initializer cannot reference the non-static fieldinstance field in a static initializer
CS0038Cannot access non-static member of outer type via nested typenested type reaching outside
CS0119Member is a type, which is not valid in the given contextname resolves to a type, not a value

CS0120 and CS0176 are mirror images, and fixing one by adding static often creates the other in code that calls the member through this or through an existing object.

Key Comparison Table

Four ways out of CS0120, and when each is right:

FixChangeKeeps stateBest for
Make the member staticadd staticno per-object statepure helpers, constants, Main entry points
Create an instancevar x = new Type();yeslogic that owns data
Inject the instanceconstructor or IServiceProvideryes, sharedASP.NET Core services, DI
Extract a local functionmove the body into Maincaptured localsone-off startup code

And where CS0120 shows up most often, in practice:

ContextCauseTypical fix
static void Maincalls an instance methodinstantiate, or make the method static
Top-level statementshelper method declared in Program without a receiverpass values as parameters
xUnit/NUnit test[Fact] on a static methodremove static from the test
Razor componentstatic method used in a markup expressionmake it an instance method
Startup configurationlambda calls an instance member of Startupuse the injected parameter
Extension methoddeclared in a non-static classmake the class static

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Decide with one question: does the member read state?

csharp
public class PriceCalculator { private readonly decimal taxRate; public PriceCalculator(decimal taxRate) => this.taxRate = taxRate; public decimal WithTax(decimal net) => net * (1 + taxRate); // instance public static decimal Percent(decimal value, decimal pct) => value * pct / 100; // static }

Percent depends on nothing but its arguments, so static is honest and removes CS0120 from every caller. WithTax depends on taxRate, so it must be an instance method; forcing it to static would only move the parameter to every call site.

2. Main, top-level statements and the generated Program class

csharp
var app = new App(); app.Run(args); public class App { public void Run(string[] args) => Console.WriteLine($"args: {args.Length}"); }

Top-level statements compile into a generated Program.Main, and any method you declare after them is a local function unless it lives in a type, which is why the helper sometimes needs an explicit receiver. Declaring partial class Program lets you add static members that the generated entry point can call:

csharp
partial class Program { static string Banner() => "demo"; }

3. Dependency injection: do not new what the container owns

csharp
public static class StartupChecks { public static async Task WarmUpAsync(IServiceProvider services) { using var scope = services.CreateScope(); var repo = scope.ServiceProvider.GetRequiredService<IOrderRepository>(); await repo.WarmUpAsync(); } }

The tempting version — a static helper holding a reference to a repository created with new — compiles once the member is made static and then fails at runtime because the repository's own dependencies are null. In ASP.NET Core, resolve from the request's IServiceProvider or from a created scope. If a controller action needs a service, inject it into the constructor; static members on a controller cannot see the injected instance.

4. Static state, thread safety and tests

Making a member static to silence CS0120 turns per-object state into process-wide state. In a web application that means concurrent requests sharing one List<T>, and in a test suite it means one test leaking into the next.

csharp
public class Sequence { private static int _next; // shared by every request public static int NextId() => Interlocked.Increment(ref _next); }

Interlocked, lock or ConcurrentDictionary are the price of static mutable state. For anything that must stay per-request, keep the instance method and pass the object through. If a member must be static for a library API, prefer static with a parameter over static with a field.

5. Nested types, records and pattern matching

A nested class cannot reach the outer instance's members without a reference:

csharp
public class Outer { private int _value = 5; public class Inner { public int Read(Outer o) => o._value; // explicit receiver, no CS0120 } }

Records behave the same way: a positional record record Money(decimal Amount, string Currency) generates instance properties, so a static factory must construct one (Money.Of(...) returning a new Money(...)) rather than assign its properties. Primary constructors on classes capture parameters as instance state too, which means a static method in the same class cannot read them.

6. CS0120 in UI code and tests

Blazor components compile to classes; a static helper cannot touch component state, StateHasChanged or injected services. In markup, @Code blocks with static methods are the usual source. In xUnit, [Fact] methods must be instance methods — a static test produces "xUnit1000: Test classes must be public" followed by CS0120-style errors when it references fixtures. NUnit is more permissive about static test methods but fixtures with [SetUp] state require an instance.

When the failing member is inside a lambda that captures a loop variable, the compiler message can point at the lambda rather than the method; extracting the lambda into a named local function makes the receiver explicit and the error obvious. For comparing two builds of the same project — before and after a static change — the text diff tool shows exactly which members moved, and a JSON serialization of the class before and after can be checked with the JSON formatter.

Common Compilation/Runtime Mistakes & Version Gotchas

Adding static to everything. It compiles and spreads the problem to callers: the next file that uses instance.Method() gets CS0176 instead, and shared state appears where none was intended.

Calling new Program() to satisfy the compiler. Legal, pointless, and it hides the design question. If a helper needs no state, make it static; if it does, the object should come from somewhere meaningful.

Confusing CS0120 with CS1061. "Does not contain a definition for" is a missing member; CS0120 is a member used through the wrong receiver. Different fixes.

Ignoring the nullable warnings that follow. After switching a member to static, NullReferenceException reports move into the static path, where there is no this to inspect in the debugger.

Version notes. C# 9 introduced top-level statements, which quietly moved Main into a generated class and created a wave of CS0120 reports in tutorials that copied console code into Program.cs. C# 10 added file-scoped namespaces and global using, changing which Program gets picked in multi-file projects. C# 11 added required members and static abstract interface members; the latter can only be called through a generic type parameter (T.Parse), never through an instance, which produces CS0120 when written the intuitive way. C# 12 primary constructors on classes capture parameters that behave like instance fields, so a static method in the same class cannot read them — a new and common source of this error in .NET 8 projects.

Reference material: Static classes and static class members and the static modifier.

Official references

primary documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.