Adam Naylor
Adam Naylor

Reputation: 6340

Is there a C# equivalent to access-modifier regions in C++

It's possible to declare variables with the below structure in C++

private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

protected float bla1;
protected float bla2;
protected float bla3;

Upvotes: 3

Views: 410

Answers (4)

Kent Boogaart
Kent Boogaart

Reputation: 178760

It's worth noting that if you have several members of the same type, you can declare them as:

protected float bla1, bla2, bla3;

Upvotes: 7

JaredPar
JaredPar

Reputation: 755219

No there is no equivalent in C# (VB and F# as well).

Personally I love this difference. I work in a very large C++ code base and there is no way to look at a particular method and know it's particular accessibility. Some of the classes have gotten so large that it takes a significant amount of page scrolling just to see the modifier.

Some coders may think that's not to bad but consider what happens when people start mixing in #if defs in the middle of the class and adding modifiers within those #if's. It makes determining the access modifier during a code review a non-trivial operation.

It's a small typing sacrifice to add the modifier inline but worth it in terms of long term readability.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502486

No. The access is specified on each declaration.

The benefit of this is that a method's location within the source file has no effect on the behaviour. That means you can move methods and properties around (e.g. to cluster related methods together) with impunity. The same isn't quite true of fields - it's possible to make the declaration order of fields matter. Admittedly it's best not to do that in the first place...

Upvotes: 9

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422132

No there isn't such a thing. In fact, it's designed to be like that to make code more readable. This applies to both C# and Java.

Upvotes: 8

Related Questions