It is good practice to keep our fields private but so far we had to create at least two methods to access or change their values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private string someString; public void SetString(string newStringName) { someString = newStringName; } public string GetString() { return someString; } //And we access it like this SomeClass stringName1 = new SomeClass (); stringName1.SetString("cool name"); Console.WriteLine(stringName1.GetString()); |
Why not star using properties? You consume properties as fields and write them (almost) as methods.
Simple property example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Field private string _flowerName; // Property signature: // public access modifier // return type // property name public string FlowerName { // get accessor // used to return value get { return _flowerName; } // set accessor // used to set value set { _flowerName = value; } } // Usage SomeClass flower = new SomeClass (); flower.FlowerName = "Rose"; Console.WriteLine(flower.FlowerName); |
But why stop there we can add more functionality to our properties, like set our string name to Upercase, return default value or check if integer is a positive number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
private string _uppercaseString; public string UppercaseString { get { return _uppercaseString != null ? _uppercaseString : "Name not available"; } set { _uppercaseString = value.ToUpper(); } } private int _positiveInteger; public int PositiveInteger { get { return _positiveInteger; } set { if (value <= 0) { Console.WriteLine("Number must be bigger than 0"); return; } _positiveInteger = value; } } // Usage SomeClass someClass = new SomeClass(); someClass.UppercaseString = "lower case name"; Console.WriteLine(someClass.UppercaseString); someClass.PositiveInteger = -1; Console.WriteLine(someClass.PositiveInteger); |
A property that has both accessors is read-write property. Properties with only get accessor are called read-only properties, properties with only get accessor are called write-only properties.
When you only need basic property without any additional logic, you could create auto-implemented property without filed (actually compiler creates one for you).
1 |
public int AutoImpelementedInt { get; set; } |
Simple isn’t it 🙂
Leave a Reply