C
C#8mo ago
Yazed0071

✅ What's the difference between Public and Private? and why would someone use it?

^
9 Replies
Jimmacle
Jimmacle8mo ago
in a class, public allows code written outside of the class definition to access whatever you declared public like a method or property and private does not it's useful to hide the inner workings of a class from outside code so you have more control over when and how it can be used
Yazed0071
Yazed00718mo ago
from a user or for you to avoid bugs?
Jimmacle
Jimmacle8mo ago
both code is easier to debug if the ways it can be accessed/modified are limited as an example, say you have a Person class with an Age property and you want to be able to make them older sure, you could make Age public but that allows other code to set any age they want, even an invalid one like a negative number instead you'd want to control their access like
public int Age { get; private set; }
public void MakeOlder(int years)
{
if (years < 0) throw new ArgumentOutOfRangeException();
Age += years;
}
public int Age { get; private set; }
public void MakeOlder(int years)
{
if (years < 0) throw new ArgumentOutOfRangeException();
Age += years;
}
this way age can only be modified in a way that the Person class has control over to make sure other code can't put it in a bad state
Yazed0071
Yazed00718mo ago
what does ?
{ get; private set;}
{ get; private set;}
Jimmacle
Jimmacle8mo ago
it means that other code can read the value of Age but can't change it, only code inside the Person class can
var x = person.Age; // ok
person.Age = 1000; // error
var x = person.Age; // ok
person.Age = 1000; // error
Yazed0071
Yazed00718mo ago
public : can read and change the value private : can't read nor change public with { get; private set; } at the end : read but not change?
Jimmacle
Jimmacle8mo ago
right, properties allow you to control the accessibility of getting and setting the value independently you could also have { private get; set; } or any other combination of access modifiers so in this case we don't want other code to set any age they want, so we make the setter private and create a method to modify age in an acceptable way
Yazed0071
Yazed00718mo ago
I see, thank you so much!
Accord
Accord8mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.