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

前端 未结 10 1680
星月不相逢
星月不相逢 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:41

    I personally prefer marking the default private and default public fields explicitly. You may well know the defaults but your brain will like verbosity whenever you quickly scan the code.

    0 讨论(0)
  • 2021-01-06 19:42

    Explicitly using private can improve readability in certain edge cases.

    Example:

            /*
            Tomorrow when we wake up from bed,
            first me and Daddy and Mommy, you, eat
            breakfast eat breakfast like we usually do,
            and then we're going to play and
            then soon as Daddy comes, Carl's going
            to come over, and then we're going to
            play a little while. And then Carl and
            Emily are both going down to the car
            with somebody, and we're going to ride
            to nursery school [whispered], and then
            when we get there, we're all going
            to get out of the car...
            */
    
            int spam;
    
            /*
            Does this style look at all familiar?
            It should!
            */
    

    Looking at this fragment you may be unsure whether you're in method or class scope.

    Using either private or underscore in field name (private int spam;, int spam_; or int _spam;) will eliminate the confusion.

    0 讨论(0)
  • 2021-01-06 19:42

    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.

    0 讨论(0)
  • 2021-01-06 19:43

    This is purely a coding standards question but, for what it's worth, I always explicitly mark private members as private.

    0 讨论(0)
提交回复
热议问题