Why is there the term "Private" in . NET?

Asked

Viewed 114 times

0

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

The statement of that:

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

It’s the same thing:

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

Why it exists and what is the purpose of it private?

  • There’s an answer I think from Maniero on the subject, to C#. I’ll look

  • This one: https://answall.com/a/236859/64969

2 answers

1


One of the places 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.

0

In addition to the reply referred by @Jeffersonquesado, which already largely clarifies the subject, I would add an answer on an exclusive question that Oce proposed.

In a free interpretation of the question:

Why is the term private if you do not declare the access modifier also makes the element private?

Facilitators and . Net conventions

It is not exclusive access modifier. 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 leaves the code thinner, without affecting its usefulness. Causing another person (or yourself) to 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 (microsoft documentation makes this clear). And it wasn’t always so in the early versions of protected was the default access modifier for some important elements. And there is no guarantee that this will not change in the next versions. Imagine the mess that caused the omission of protected when migrating the system to a new version when inherited classes stopped "seeing" elements of their ancestor...

Explicitude

It makes it explicitly clear what its intention is regarding the accessibility of that element. Thinking of stable and evolutionary code, if these conventions change.

I hope this helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.