Any reason to write the “private” keyword in C#?

后端 未结 9 574
梦谈多话
梦谈多话 2020-12-04 18:54

As far as I know, private is the default everywhere in C# (meaning that if I don\'t write public, protected, internal

9条回答
  •  渐次进展
    2020-12-04 19:12

    AFAIK, private is the default everywhere in C#

    Not quite - the default is "the most restricted access available for this declaration". So for example, with a top-level type the default is internal; for a nested type the default is private.

    So, what's the reason to write that keyword, or why does it even exist?

    It makes it explicit, which is good for two reasons:

    • It makes it clearer for those who don't know the defaults, as per your question (I've never liked this argument, personally, but I figured it's worth mentioning)
    • It gives an impression that you've deliberately decided to make it private, rather than just gone with the defaults.

    As for your last part:

    Moreover is there a case where writing "private" (alone) will change the accessibility of the member?

    Yes, for making half of a property more restrictive than the other:

    // Public getter, public setter
    public int Foo { get; set; }
    
    // Public getter, private setter
    public int Bar { get; private set; }
    

    I used to go with defaults everywhere I could, but I've been convinced (partly by Eric Lippert) that making it clear that you've thought about it and decided to make something private is a good idea.

    Personally I wish there were a way of doing that for sealed / unsealed, too, for type declarations - possibly not even have a default. I suspect that many developers (myself included if I'm not careful) leave classes unsealed just because it's less effort than making them sealed.

提交回复
热议问题