Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class is private or internal default in .net? [duplicate]

Tags:

c#

.net

Possible Duplicate:
Why Visual Studio doesn’t create a public class by default?

msdn link tell us that

http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx

Default member accessibility of Class is private

Please explain whether it is Internal or Private by default ?

like image 955
Neo Avatar asked Dec 01 '25 14:12

Neo


2 Answers

The default for all members is "the most private you could specify"1.

So nested types are private by default, but top-level types are internal by default:

namespace Foo
{
    class ThisIsInternal
    {
        class ThisIsPrivate
        {
        }
    }
}

The rules are the same for all types - it doesn't matter whether it's a class, interface, struct, enum or delegate.


1 with the slight exception of specific property getters/setters, where you can only be explicit about one part of the property when you're making it more private.

// The getter is public, the setter is private
public string Foo { get; private set; }
like image 57
Jon Skeet Avatar answered Dec 03 '25 05:12

Jon Skeet


It may seem odd that a class is sometimes internal by default (when top level) and sometimes private (when nested). However, this simply means that all access modifiers are maximally restrictive by default. This also means that almost all usages of the word private are redundant - only those on property accessors are meaningful (they can restrict access to an otherwise non-private property).

So I prefer to think of the default as the consistent one - namely being conceptually private, and the keywords being inconsistent - internal sometimes means keep local to the context, and sometimes means grant access to the entire assembly :-). And private almost always means nothing - it's pure boilerplate which is therefore best left out (except in property accessors).

like image 26
Eamon Nerbonne Avatar answered Dec 03 '25 07:12

Eamon Nerbonne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!