Why I can set value for a property that only has a GET

Viewed 65

Sorry it is a dumb question, just learning from a book and I saw this code:

public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

My question is how is this working? There is no set; and we are assigning a value to that property.

1 Answers

This is known as an "Auto-Implemented Property" ("auto property", for short), because there is no "backing field" (or get accessor logic) defined, so the compiler creates a backing field automatically.

A property ("auto" or otherwise) with only a get accessor is a read-only property.

A read-only auto property may be set (initialized) in the constructor, as shown.

Auto properties may also be initialized when declared:

public IConfiguration Configuration { get; } = [some IConfiguration];
Related