Home > database >  How does a property without setter allow value to be assigned?
How does a property without setter allow value to be assigned?

Time:11-26

In C#, property can be declared with getter and setter. If there is no setter then it shouldn't allow to set?

But this .net core 3.1 example tutorial shows value assigned to such a property. How is this allowed?

Code:

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

CodePudding user response:

An read-only property can only be set:

  • If it's an auto-implemented property (i.e. the property body just has { get; })
  • When the setting the property is within the constructor

The read-only property is implemented as a read-only field, and when the property is set within the constructor, the read-only field is set directly.

So the code you've posted is equivalent to:

public class Startup
{
    private readonly IConfiguration _configuration;
    public IConfiguration Configuration => _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
  •  Tags:  
  • c#
  • Related