Pretty straight forward here. I want to know when a class in c# (and probably any oo-language) is okay being neither "public", "private", "protected"...
I am asking this question because when I create a class in Visual studio it generates me a class stub with no accessibility modifier like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myNamespace
{
class myClass
{
}
}
And every time I don't give that much attention to this part of the code and make a reference to it somewhere else and finally run and get a Inconsistent accessibility error.
So in what situation a class can, and maybe should be just "class" and not public or anytyhing? I'm having hard time finding a place where it would be a good thing.
Is there a default accessibility modifier?
The general rule in C# is "the default is as private as you can explicitly declare it". So:
namespace Foo
{
class Bar // Implicitly internal class Bar
{
int x; // Implicitly private int x
void Baz() {} // Implicitly private void Baz() {}
class Nested // Implicitly private class Nested
{
}
}
}
... you can't declare a top-level (non-nested) class as private
, but you can declare a nested class as private.
The only case in which this rule is sort of broken is with properties, where the default for a getter or setter is "the same as the overall property declaration" and you can only specify a more restrictive modifier on a getter/setter. For example:
internal string Foo { get; private set; }
has an internal getter. The overall property follows the first rule, however - so it defaults to being private.
See more on this question at Stackoverflow