get / set incapsulation
1 2 3 4 5 6 7 8 |
class SomeClass{ private int id; // field public int GetID() { return id; } public void SetID(int IDValue) {/*someLogicHere;*/ id = IDValue; } } |
properties incapsulation
1 2 3 4 5 6 7 8 9 10 11 12 |
class SomeClass2 { private int id; // << field public int IDValue { // << property get { return id; } set { /*someLogicHere;*/ id = IDValue; } } } |
properties incapsulation with value word
1 2 3 4 5 6 7 8 9 10 11 12 |
class SomeClass3 { private int id; // << field public int IDValue { // << property get { return id; } set { /*someLogicHere;*/ id = value; } // << value is contextual here } } |
automatical properties
1 2 3 4 5 |
class SomeClass4 { private int id; // << field public int ID { get; set; } } |
also
1 2 3 4 5 |
class SomeClass4 { private int id; // << field public int ID { get; protected set; } // only for family of classes } |
if property has object – it must be initialized
1 2 3 4 5 6 7 8 9 10 |
class Car { } class SomeClass5 { private Car c; // << field public Car C { get; set; } // will create c with null reference! Must be created in constructor public SomeClass5() { c = new Car(); } public SomeClass5(Car c) { C = c; } } |
123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace incapsulation { class Program { static void Main(string[] args) { SomeClass sc = new SomeClass(); sc.someMethod(); // << incapsulated } } class SomeClass { public string someField; public void someMethod() { Console.WriteLine("do something with someField"+someField); } } } |