C# – Should You Use Private on Fields and Methods?

ccode-qualitycoding-styleprogramming practices

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?

Best Answer

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
Related Topic