Search code examples
c#oopaccess-modifiersinformation-hidingpublic-members

Why aren't all fields/properties/methods public?


I know this may sound stupid, but i really want to know :) im learning c# currently,

and as you know you need to set "object"(button,label,text,variable, etc.) public or whatever you like.

However, you still need to write a code like this:

// my point is you cant just type label1.text you need to type class.label1.text
// so there is no chance of getting bugged
//because there is label1 in each of forms/classes
 class Classlol = new class();
 classlol.label1.blabla

So what's the point of making it unreachable in other forms ? why every thing isnt public or its not public by default ?

Thanks.


Solution

  • The point of using classes is to be able to separate your code into logically related pieces. This makes your code easier to understand and maintain.

    For example, if you need to modify code in a class, you can focus more on the way that class functions and less on other parts of your project. However, public members of your class limit this separation somewhat because, if you modify a public member, that can affect other parts of your project.

    Keeping as much of your class private as possible (while still usable from your application) maximizes the separation between it and the rest of your application. It makes it easier to think about only the logic in the class you are working on, and it allows you to modify those private members without having to think what other parts of your application might be affected.