What for should I mark private variables as privat

2020-03-06 02:31发布

As far as I know, in C# all fields are private for default, if not marked otherwise.

class Foo
{
  private string bar;
}

class Foo
{
  string bar;
}

I guess these two declarations are equal.

So my question is: what for should I mark private variables as private if they already are private?

10条回答
在下西门庆
2楼-- · 2020-03-06 03:30

Up to you. Do what's best for readability or makes sense in your case. I mark them as private just to make it clear though.

查看更多
等我变得足够好
3楼-- · 2020-03-06 03:32

I think for readability it is always best to be explicit.

As a side, You may wish to have a look at a visual studio plug-in called Code Style Enforcer (http://joel.fjorden.se/static.php?page=CodeStyleEnforcer) which uses the dxCore extensions to provide real-time feedback on your codes adherence to coding standards (fully customisable).

查看更多
别忘想泡老子
4楼-- · 2020-03-06 03:33

Now; fields should pretty-much always be private anyway, so it is an edge case whether you should bother.

For the wider subject, I remember a comment by Eric Lippert - essentially saying that given a method / class / whatever:

void Foo() {}
class Bar {}

Then it isn't clear whether they are private/internal deliberately, or whether the developer has thought about it, and decided that they should be private/internal/whatever. So his suggestion was: tell the reader that you are doing things deliberately instead of by accident - make it explicit.

查看更多
做个烂人
5楼-- · 2020-03-06 03:34

Yes they are equal but I like to mark private variables as private, I think it improves reading.

also I use this common notation for private members, it's very useful :

private string _bar;
查看更多
登录 后发表回答