What is the difference between a field and a property? Why should i use Encapsulation? How to create Getter and Setter methods? If you are asking yourself these questions, you are in the right place.
Field
In recents posts, we declared variables as below:
byte ThisIsAByte = 25;
int number =2021;
string str= "Hey! this is a string";
short thisIsAShort =3200;
float thisIsAFloat = 33.3f;
double thisIsADouble = 11.1d;
sbyte ThisIsASignedByte = -10;
When we declare variables in a class or struct, They are called fields. In the code below, i created a class and many fileds. However, because of public access identifier, you can get and change these files within the class, within the derived class, within the Non-derived class(same assembly). Anyone access fields from anywhere that's why there is a lack of security. Your co-workers and you might change vital fields accidentally.
class ThisClassContainsFields {
public byte thisIsAByte = 25;
public int number = 2021;
public string str = "Hey! this is a string";
public short thisIsAShort = 3200;
public float thisIsAFloat = 33.3f;
public double thisIsADouble = 11.1d;
public sbyte thisIsASignedByte = -10;
}
Encapsulation
It is a way to hide the variables and data from other classes.
Property, Getter and Setter
It allows you to choose how you want to expose your data to outside objects. In this way, you get ad set values. We will write the fields with properties that expose fields.
class ThisClassContainsFields {
byte _thisIsAByte = 25;
int _number = 2021;
string _str = "Hey! this is a string";
short _thisIsAShort;
float _thisIsAFloat = 33.3f;
double _thisIsADouble = 11.1d;
sbyte _thisIsASignedByte = -10;
// Here you see getter and setter methods. Other classes can't access the fields above.
public byte ThisIsAByte { get => _thisIsAByte; set => _thisIsAByte = value; }
public int Number { get => _number; set => _number = value; }
public string Str { get => _str; set => _str = value; }
public short ThisIsAShort { get => _thisIsAShort; set => _thisIsAShort = value; }
public float ThisIsAFloat { get => _thisIsAFloat; set => _thisIsAFloat = value; }
public double ThisIsADouble { get => _thisIsADouble; set => _thisIsADouble = value; }
public sbyte ThisIsASignedByte { get => _thisIsASignedByte; set => _thisIsASignedByte = value; }
}