Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am somewhat new to C# and just found out that: in C# all of the fields and methods in a class are default private. Meaning that this:

class MyClass
{

string myString

}

is the same as:

class MyClass
{

private string myString

}

So because they are the same should I ever use the keyword private on fields and methods? Many online code samples use the keyword private in their code, why is that?

share|improve this question
33  
Well, for starters, it makes it obvious that you intended to make your field private, rather than just forgetting to include a scope specifier. –  KChaloux Aug 4 at 16:39
3  
I'm uncomfortable not using private. It makes for less cognitive dissonance for me if I can always expect to see the scope specifier as the first part of an identifier declaration. It takes my mind less time to read "private" than it does to figure out that the first word is not a scope specifier and, oh yeah, that means that it is a private member declaration. Writing code is also about having to read it later. –  Robert Harvey Aug 4 at 16:57
3  
@RobertHarvey It may also be completely subjective; when coding in C++, I always omitted everything that was optional, because I felt it distracted me, until I realized that other people reading my code may be accustomed to more verbose coding conventions. So it's a matter of taste (on a personal project) and convention (when collaborating). –  marczellm Aug 4 at 17:12
2  
@gnat I am not sure this is a duplicate of that question. Are you sure you posted the right link? –  maple_shaft Aug 5 at 10:46
3  
@gnat It is a stretch to ask why one would explicitly declare the private keyword in their code is a question about coding style. This question is far more specific than that. I feel that while a canonical answer might cover a different question, a more specific question can sometimes deserve its own answer. –  maple_shaft Aug 5 at 10:53

4 Answers 4

up vote 35 down vote accepted

Just because you can omit linefeeds and indentations and your C# compiler will still understand what you want to tell it, it's not automatically a good idea to do that.

using System; namespace HelloWorld{class 
Hello{static void Main(){Console.WriteLine
("Hello World!");}}}

is much less readable to the human reader than:

using System;
namespace HelloWorld
{
    class Hello 
    {
        static void Main() 
        {
            Console.WriteLine("Hello World!");
        }
    }
}

And that's the whole point here—programs are written for two audiences:

  • The compiler or interpreter.
  • Yourself and other programmers.

The latter is the one who needs to understand and quickly grasp the meaning of what is written. Because of this there are a few good practices that have emerged over the years and are more or less commonly accepted quasi-standards. One of them is putting explicit scope keywords, another example is putting extra parentheses around complex expressions, even in cases where they would not be needed syntactically, like:

(2 + 5) & 4
share|improve this answer
1  
+1 In particular for that last point. Whilst strictly speaking programmers should know the order of operations for their language, I always try to add extra parenthesis where possible because in the past I've found myself wasting several seconds trying to think which operation comes first and whether or not an expression evaluates the way I think it does. Occasionally the answer is "No, I've got it wrong" and those occasions can be avoided with reasonable use of brackets, particularly when you consider cases such as 5 + 5 * 5 is 30, not 50 as some might expect at first glance. –  Pharap Aug 5 at 10:29
    
+1. There is a slight mental hiccup for me when I don't see explicit visibility modifiers. I have to think for a split second, "Is the default public or private?" simply because I always use the modifiers, and when someone doesn't, it throws me off. –  Greg Bair Aug 7 at 11:06
5  
You mean **private** static void Main() ? :) –  Jesse C. Slicer Aug 7 at 19:35

C# is not the only programming language for .NET; other languages can and do have different default accessibility in various contexts. Specifying private will make it clear to anyone reading the code that such accessibility is intended, whereas omitting the spec leaves open the question of whether the member might have been e.g. intended to be usable within the assembly [as would be the default in VB.NET]. Being explicit may be especially useful if one uses multiple languages with different rules.

With regard to whether private or protected should be favored in the absence of a particularly compelling argument in favor of the other, the decision should be based upon whether it is more likely that exposing a member may make it possible for a derived class to do something useful that would otherwise not be possible, or that it would prevent future versions of a class from modifying their internal data structures in a fashion that would be more efficient. One may see examples of both situations in List<T>.

In some cases, if one has a list of aggregates (e.g. Point structures) it may be useful to update items in-place. If List<T> exposed its backing store to derived classes, one could easily define an EditableList<T> with a method:

delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);

void ActOnItem<TParam>(int index, ref TParam param, ActByRef<TParam> proc)
{
  .. test index, then...
  proc(ref _arr[index], ref proc);
}

which would could then be invoked using something like:

int adjustmentAmount = ...;
myList.ActOnItem(index, ref adjustmentAmount, 
  (ref Point pt, ref int dx) => pt.X += dx );

Such a method could allow efficient updates even with relatively large structure types [since no copying would be required]. The fact that List<T> does not expose its internals makes it impossible to derive a class which could implement such an operator efficiently.

On the flip side, although so far as I know Microsoft has not yet exploited this ability, having the backing store be private would make it possible for a future version of List<T> to split the backing store into pieces that were smaller than 85K when using most data types, or smaller than 1000 items when using double. Such a split would not be possible if List<T> had exposed the backing store to derived classes.

share|improve this answer
    
As fields are default private I do not expect the C# compiler's Common Intermediate Language output of int myField and private int myField to be different. So I do not believe not adding private leaves it open to interpretation for other .NET languages. –  Roy T. Aug 5 at 12:11
    
@RoyT.: My point was that if multiple languages are in use, it may not be clear that a member with an omitted access specifier was intended to have the access that would have been the default in a different language. –  supercat Aug 5 at 14:53
    
ah I understand now. You were so explicitly referring to other .NET languages that I understood it as programs not understanding, not people. –  Roy T. Aug 5 at 16:44
1  
@RoyT.: I edited the first paragraph; does that make it clearer? –  supercat Aug 5 at 17:47

Yes you should use it : ) The private keyword is used because it is generally accepted practice and removes all doubt about the intended scope of a class member.

Readability is very important with code, especially when working in a team. If you want to look at code readability further, a good reference book I can recommend is The Elements of C# Style.

share|improve this answer

Question:

"Should you ever use private on fields and methods in C#?"

Quick Answer:

Yes, but, it depends in your code logic.

Long Boring Extended Answer:

I suggest, always specify vissibility for members.

I think It is a good approach to declare members, by default, as "private".

In real world, I use "protected", instead.

Sooner, or later, that hidden member, could be used by a subclass.

Sometimes, a good question, can be better answered, by asking the opposite question.

The opposite question, to your question, could be something like:

"Should I use always public access modifier on fields & methods in C#"

In other programming languages you can "promote" protected to public, depending on your design.

I use a lot of (visual) control deep hierarchy libraries, where, some members (properties, methos) are required.

Sometimes, is better to have them public, sometimes don't.

share|improve this answer
5  
Using protected as your go-to specifier can be bad. It potentially opens up the superclass to manipulation that might not be appropriate, as a subclass might be able to work around error checks or restrictions put in place in the superclass. Even if that is not the case, it still pollutes subclasses with additional in-scope variables that are redundant (e.g. protected variable with an accessor now provides two ways to change it in a subclass). –  Snowman Aug 4 at 20:53
2  
-1: Does not attempt to address the question. –  mattnz Aug 4 at 21:26
1  
Public and protected are IMHO closer than private and protected. They are part of the interface of the class. Private members are black box internal state only. –  Petter Aug 4 at 22:03
    
+1 because I like to declare private even if its not needed. Good code is much about readability as is functionality. –  Phil Vallone Aug 4 at 22:16
2  
-1 Using protected as default is horrible advice. You can always increase the visibility of members later but not the other way around without breaking code (when people are using your code) . –  Oliver Weiler Aug 5 at 8:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.