Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set properties of a class only through constructor

I am trying to make the properties of class which can only be set through the constructor of the same class.

like image 721
Srikrishna Sallam Avatar asked Mar 01 '10 16:03

Srikrishna Sallam


People also ask

What is readonly property in C#?

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.

Why we use get set property in C#?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.

What is getter setter in C#?

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.

What is a constructor C#?

Constructors are special methods in C# that are automatically called when an object of a class is created to initialize all the class data members. If there are no explicitly defined constructors in the class, the compiler creates a default constructor automatically.


2 Answers

This page from Microsoft describes how to achieve setting a property only from the constructor.

You can make an immutable property in two ways. You can declare the set accessor.to be private. The property is only settable within the type, but it is immutable to consumers. You can instead declare only the get accessor, which makes the property immutable everywhere except in the type’s constructor.

In C# 6.0 included with Visual Studio 2015, there has been a change that allows setting of get only properties from the constructor. And only from the constructor.

The code could therefore be simplified to just a get only property:

public class Thing {    public Thing(string value)    {       Value = value;    }     public string Value { get; } } 
like image 135
stephenbayer Avatar answered Sep 27 '22 19:09

stephenbayer


Make the properties have readonly backing fields:

public class Thing {    private readonly string _value;     public Thing(string value)    {       _value = value;    }     public string Value { get { return _value; } } } 
like image 20
David Morton Avatar answered Sep 27 '22 21:09

David Morton