What for should I mark private variables as private if they already are?

前端 未结 10 1881
星月不相逢
星月不相逢 2021-01-06 18:43

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;
}
         


        
10条回答
  •  感动是毒
    2021-01-06 19:28

    I've been on the fence for a while about this. I used to argue for leaving it implicit, but now I think I'm tipped over towards making it explicit.

    Reasons for leaving it implicit:

    • It means there's a bigger difference for non-private members (or anything with more access than the default); this highlights the difference when reading the code

    Reasons for making it explicit:

    • Some developers may not know the defaults: making it explicit means it's clear to everyone
    • It shows you've actively made a decision, rather than just leaving it up to the default

    These latter points are basically the ones made by Eric Lippert when we discussed it a while ago.

提交回复
热议问题