Why is the term "Private" in .NET? [duplicate]

0

Declaring variables without specifying the access level of the variable in C # and Visual Basic .NET ends up making private , only the type / location where it was created can access and / or modify it. However, there is also the keyword private , but I find no utility in it.

The declaration of this:

// C#
string foo = "bar";
// VB
Dim foo As String = "bar"

It's the same as that:

// C#
private string foo = "bar";
// VB
Private Dim foo As String = "bar"

Why does it exist and what is the purpose of this private ?

    
asked by anonymous 22.02.2018 / 04:00

2 answers

1

One of the sites where the private modifier is explicitly useful is when it has a read-only public property.

public string Nome { get; private set; }

This allows you to assign values to the property within the class but not outside it.

    
22.02.2018 / 09:59
0

In addition to the response referenced by @ JeffersonQuesado, which already clarifies the subject, I would add an answer on a unique issue that you proposed.

In a free interpretation of the question:

  

Why does the term private exist if you do not declare the access modifier also causes the element to be private?

.Net Facilitators and Conventions

There is no access modifier exclusivity. For this same reason, you do not declare a constructor in your class and the compiler "infers" that there is an empty constructor available. Or a method has optional parameters and you do not declare in the call of this method.

This all makes the code leaner, without affecting its usefulness. Making another person (or yourself) have less data presented to interpret the code, for example.

It's not always like this

Not all elements are private by default, some are public or internal ( the microsoft documentation makes this clear ). And it was not always the case in the early versions of protected was the default access modifier for some important elements. And nothing guarantees that this will not change in the next versions. Imagine the mess that caused the protected to skip when migrating the system to a new version when inherited classes failed to "see" elements of their ancestor ...

Explicide

It makes it explicitly clear what your intention is regarding the accessibility of that element. Thinking of a stable and evolutionary code, if these conventions change you will have one less job.

Hope this helps.

    
22.02.2018 / 09:48