Lee Toffolo
Lee Toffolo

Reputation: 134

Accessibility levels in a single class project

I have a very simple utility program I have built in C#. It only has one namespace and one class. I am just wondering what the best practice is in regards to adding accessibility keywords to the methods/variables in this context. Is it okay to just leave the accessibility keyword out here? It seems to me that adding one will be unproductive, but the methods just feels so "naked" without one.

Upvotes: 1

Views: 129

Answers (4)

user7396598
user7396598

Reputation: 1289

Mark them as they would be used if they were in a larger application.

You never know when you might migrate this code into a larger app.

Also, 6 or 7 letters to be explicit and not have yourself or someone else later on wondering what your intentions were seems a small price to pay

Upvotes: 1

Dave
Dave

Reputation: 3017

Best Practice is usually quoted as this:

Make everything as restrictive as possible and only unrestrict when neccessary

The defaults are this in C#

  • classes: internal
  • class members: private

Private classes unless nested are rarely useful, but never mind that.

Now the last bit is my opinion. Code readability and ease of understanding is sooooo important and so I would say that it best to explicitly put the access levels in even if they are the same as the default

Upvotes: 2

Joe Sewell
Joe Sewell

Reputation: 6640

Leaving off an access modifier when declaring a code element means the compiler will provide a default access level. In your case, the class (a top-level type) would be internal and its members would be private. This is suitable for a standalone utility which you do not expect to be referenced by any other code (internal means "only this assembly (EXE/DLL) can see this" and private means "only the class/struct that declares this can see this"). Whether you want to include or leave off the keywords is a matter of style.

Upvotes: 1

Jon Hanna
Jon Hanna

Reputation: 113382

Leaving them out is the same as whatever the most restrictive possible is (so private for within a class and internal for a class itself within a namespace).

Technically it makes no difference whether you explicitly write private or leave it out. As a matter of convention it's more common to be explicit (include the private) and it's good to get into the habit of following common convention, so worth doing for that matter alone.

Upvotes: 1

Related Questions