We have created a property named “Age” without a field and
encapsulated it with "private" access modifier to restrict
directly access on it. So, the "Age" property is unreachable
from the outside of the given class (The class that we gonna
use in this example is “Person”). Thats what "private" access
modifiers do. This process is called "Encapsulation".
It's a meaningful identifier since we are "encapsulating"
the given property and hiding it from the outer-space.
With the encapsulation in this example, you are not able to
change the "Age" property by directly addressing it. For example:
Person p1 = new Person();
p1.Age = 33;
/*That will not work as expected.
If we could use the "public" access modifier, that expression
could work properly. Lets see another example:
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
class Person{
private int Age = 30;
public void IncAge(int n){
Age += n;
}
public void DecAge(int n){
Age -= n;
}
public int GetAge(){
return Age;
}
}
static void Main(){
Person p1 = new Person();
p1.DecAge(4);
Console.WriteLine(p1.GetAge());
p1.IncAge(10);
Console.WriteLine(p1.GetAge());
p1.Age = 23;
/*
As you can see, this line will cause an error too since
"Age" Property's access modifier has set to "Private".
It can’t be reached from this Main Method or any other
methods in your project for reasons that i have wrote above.
*/
}
}
}
Hiç yorum yok:
Yorum Gönder