10

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?

gnat
  • 20,543
  • 29
  • 115
  • 306
user3210251
  • 111
  • 1
  • 4

4 Answers4

40

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
JensG
  • 2,473
6

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.

supercat
  • 8,629
3

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.

-4

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.

umlcat
  • 2,206