readonly C# with Example
The readonly keyword is a field modifier. When a field declaration includes a readonly modifier, assignments to that field can only occur as part of the declaration or in a constructor in the same class. The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. The readonly keyword is often used when injecting dependencies. class Person { readonly string _name; readonly string _surname = "Surname"; Person(string name) { _name = name; } void ChangeName() { _name = "another name"; // Compile error _surname = "another surname"; // Compile error } } Note: Declaring a field readonly does not imply immutability. If the field is a reference type then the content of the object can be changed. Readonly is typically used to prevent having the object being overwritten and assigned only during instantiation of that object. Note: Inside the constructor a readonly field can be reassigned public class Car { public double Speed {get; set;} } //In code private readonly Car car = new Car(); private void SomeMethod() { car.Speed = 100; }