✅ What's the difference between Public and Private? and why would someone use it?
^
9 Replies
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
from a user or for you to avoid bugs?
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
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
what does ?
it means that other code can read the value of Age but can't change it, only code inside the Person class can
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?
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 wayI see, thank you so much!
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.