C #: from medium to advance level [Access modifier and Properties (Part II)]
In this article we see what are the Properties and how work.
The main reason why we use properties, is create a getter / setter fields, but with less code!
The logic is the same as what we saw in the previous article.
I use same example I used before.
We have private field, and two methods : GetDamge and SetDamage.
Now, we change this into a property!
The syntax is this
Let’s look at this.
We have our private fields, then we create a public field of same type (int in this case) with SAME NAME but in Pascal Case.
As we can see, the logic is the same as before. The difference, in addition to the syntax, is that here we use two keywords of C# : get and set.
The get part simply returns the value we have.
Instead set part uses another keyword: value, and it means that every new value we pass is copied over _damage.
We can also use the Auto-implemented Properties, like this
When we use Auto-implemented Properties, at runtime C# create a private field behind the scene for us with a get and set.
One of the best example I have seen for understand how use logic in properties is calculate the birthday of one person.
we have our Birthday property with get and set
Now, if we create a property Age, we simply calculate it in base of our Birthday!
So we have our Age property
Inside here we write the logic to calculate how many years we have.
P.S. : I never talk about DateTime Class. The only thing we have to know is that this Class manage Time, and if we need to calculate a difference between dates, the result is ALWAYS a TIMESPAN.
Back to our property, this is great example because as you can see I use logic to calculate my Age, so I don’t need a set. Because the calculation is based on my Birthday.
If I make a try
Everything good, but we can improve more.
At this time we can set the BirthDay from everywhere, because we have a get / set auto-property.
So, if we make the set PRIVATE, what happen?
Now we have a problem, because if the set is private, the field can only be read within the Enemy Class.
So if we’re going to set up BirthDay, where can we do that?
There is only one place.
Inside Enemy Class, in the Constructor.
With this, we simply pass the birthDay parameter when we create an Enemy
Everything work fine, but we use an auto property with a get and a private set, and another property, which READ that private set, and calculate the Age in base of it.
Everything well ENCAPSULATED, nothing can be read from outside.