If you want to create fields in a class, weather public or private and want them to be un-mutable from anywhere within or outside of the class except from the class constructor or at field level declaration then you can make use of readonly modifier:
using System; public class SomeClass { public readonly string FieldA = string.Empty; public SomeClass(string valueForFieldA) { this.FieldA = valueForFieldA; } public void SomeFunction(string someValue) { //this.FieldA = someValue; This will not work } }
Points to remember:
- Trying to modify the value of FieldA after instantiating SomeClass will not work.
- Remember readonly keyword (modifier) is only for fields not for properties!
No comments:
Post a Comment
Your comments are highly appreciated!