[c#] In C#, what is the difference between public, private, protected, and having no access modifier?

All my college years I have been using public, and would like to know the difference between public, private, and protected?

Also what does static do as opposed to having nothing?

This question is related to c# .net asp.net access-modifiers

The answer is


A graphical overview (summary in a nutshell)

Visibility

Since static classes are sealed, they cannot be inherited (except from Object), so the keyword protected is invalid on static classes.



For the defaults if you put no access modifier in front, see here:
Default visibility for C# classes and members (fields, methods, etc.)?

Non-nested

enum                              public
non-nested classes / structs      internal
interfaces                        internal
delegates in namespace            internal
class/struct member(s)            private
delegates nested in class/struct  private

Nested:

nested enum      public
nested interface public
nested class     private
nested struct    private

Also, there is the sealed-keyword, which makes a class not-inheritable.
Also, in VB.NET, the keywords are sometimes different, so here a cheat-sheet:

VB vs. CS equivalents


I think it is related to good OOP design. If you are a developer of a library you want to hide the inner workings of your library. That way, you can modify your library inner workings later on. So you put your members and helper methods as private, and only interface methods are public. Methods that should be overwritten should be protected.


Those access modifiers specify where your members are visible. You should probably read this up. Take the link given by IainMH as a starting point.

Static members are one per class and not one per instance.


Hmm.

See here: Access Modifiers.

In a nutshell:

Public gives the method or type complete visibility from other types/classes.

Private allows only the type containing the private method/variable access to the private method/variable (note that nested classes also have access to the containing classes private methods/variables).

Protected is similar to private except derived classes can also access protected methods.

"Nothing" is VB.NET's equivalent to null. Although if you're referring to "nothing" meaning "no access modifier", then it depends, although a very rough rule of thumb (certainly in C#) is that if you don't explicitly specify an access modifier, the method/variable declaration is usually as restricted as it can be. i.e.

public class MyClass
{
    string s = "";
}

is effectively the same as:

public class MyClass
{
    private string s = "";
}

The linked MSDN article will offer a fully description when there's no access modifier explicitly specified.


enter image description here

using System;

namespace ClassLibrary1
{
    public class SameAssemblyBaseClass
    {
        public string publicVariable = "public";
        protected string protectedVariable = "protected";
        protected internal string protected_InternalVariable = "protected internal";
        internal string internalVariable = "internal";
        private string privateVariable = "private";
        public void test()
        {
            // OK
            Console.WriteLine(privateVariable);

            // OK
            Console.WriteLine(publicVariable);

            // OK
            Console.WriteLine(protectedVariable);

            // OK
            Console.WriteLine(internalVariable);

            // OK
            Console.WriteLine(protected_InternalVariable);
        }
    }

    public class SameAssemblyDerivedClass : SameAssemblyBaseClass
    {
        public void test()
        {
            SameAssemblyDerivedClass p = new SameAssemblyDerivedClass();

            // NOT OK
            // Console.WriteLine(privateVariable);

            // OK
            Console.WriteLine(p.publicVariable);

            // OK
            Console.WriteLine(p.protectedVariable);

            // OK
            Console.WriteLine(p.internalVariable);

            // OK
            Console.WriteLine(p.protected_InternalVariable);
        }
    }

    public class SameAssemblyDifferentClass
    {
        public SameAssemblyDifferentClass()
        {
            SameAssemblyBaseClass p = new SameAssemblyBaseClass();

            // OK
            Console.WriteLine(p.publicVariable);

            // OK
            Console.WriteLine(p.internalVariable);

            // NOT OK
            // Console.WriteLine(privateVariable);

            // Error : 'ClassLibrary1.SameAssemblyBaseClass.protectedVariable' is inaccessible due to its protection level
            //Console.WriteLine(p.protectedVariable);

            // OK
            Console.WriteLine(p.protected_InternalVariable);
        }
    }
}

 using System;
        using ClassLibrary1;
        namespace ConsoleApplication4

{
    class DifferentAssemblyClass
    {
        public DifferentAssemblyClass()
        {
            SameAssemblyBaseClass p = new SameAssemblyBaseClass();

            // NOT OK
            // Console.WriteLine(p.privateVariable);

            // NOT OK
            // Console.WriteLine(p.internalVariable);

            // OK
            Console.WriteLine(p.publicVariable);

            // Error : 'ClassLibrary1.SameAssemblyBaseClass.protectedVariable' is inaccessible due to its protection level
            // Console.WriteLine(p.protectedVariable);

            // Error : 'ClassLibrary1.SameAssemblyBaseClass.protected_InternalVariable' is inaccessible due to its protection level
            // Console.WriteLine(p.protected_InternalVariable);
        }
    }

    class DifferentAssemblyDerivedClass : SameAssemblyBaseClass
    {
        static void Main(string[] args)
        {
            DifferentAssemblyDerivedClass p = new DifferentAssemblyDerivedClass();

            // NOT OK
            // Console.WriteLine(p.privateVariable);

            // NOT OK
            //Console.WriteLine(p.internalVariable);

            // OK
            Console.WriteLine(p.publicVariable);

            // OK
            Console.WriteLine(p.protectedVariable);

            // OK
            Console.WriteLine(p.protected_InternalVariable);

            SameAssemblyDerivedClass dd = new SameAssemblyDerivedClass();
            dd.test();
        }
    }
}

A status of Private indicates that variables can only be accessed by objects of the same class. Protected status extends that access to include descendants of the class as well.

"from the above table we can see the deference between private and protected... am think both are same ....so what the need for that two separate command"

Check MSDN link for more information


Regarding the question of Nothing

  • Namespace types are internal by default
  • Any type member, including nested types are private by default

Public - If you can see the class, then you can see the method

Private - If you are part of the class, then you can see the method, otherwise not.

Protected - Same as Private, plus all descendants can also see the method.

Static (class) - Remember the distinction between "Class" and "Object" ? Forget all that. They are the same with "static"... the class is the one-and-only instance of itself.

Static (method) - Whenever you use this method, it will have a frame of reference independent of the actual instance of the class it is part of.


All access modifiers' descriptions for C#

enter image description here


Yet another visual approach of the current access modifier (C# 7.2). Hopefully the schema helps to remember it easier
(click the image for interactive view.)

interactive access modifiers svg

Outside Inside

If you struggle to remember the two-worded access modifiers, remember outside-inside.

  • private protected: private outside (the same assembly) protected inside (same assembly)
  • protected internal: protected outside (the same assembly) internal inside (same assembly)

C# has, in total, 6 access modifiers:

private: The member declared with this accessibility can be visible within the containing type, it is not visible to any derived types, other types in the same assembly or types outside of the containing assembly. i.e., access is limited to the containing type only.

protected: The member declared with this accessibility can be visible within the types derived from the containing type within the containing assembly, and the types derived from the containing type outside of the containing assembly. i.e., access is limited to derived types of the containing type.

internal: The member declared with this accessibility can be visible within the assembly containing this member, it is not visible to any assembly outside of the containing assembly. i.e., access is limited to containing assembly only.

internal protected: The member declared with this accessibility can be visible within the types derived from the containing type within or outside of the containing assembly, it is also visible to any types within the containing assembly. i.e., access is limited to containing assembly or derived types.

public: The member declared with this accessibility can be visible within the assembly containing this member, or any other assembly that references the containing assembly. i.e., access is not limited.

In C# 7.2, a new level of accessibility was added:

private protected: The member declared with this accessibility can be visible within the types derived from this containing type within the containing assembly. It is not visible to any types not derived from the containing type, or outside of the containing assembly. i.e., the access is limited to derived types within the containing assembly.

Source including a sample code of the new private protected access modifier


mmm...

Static means that you can access that function without having an instance of the class.

You can access directly from the class definition.


Careful! Watch the accessibility of your classes. Public and protected classes and methods are by default accessible for everyone.

Also, Microsoft isn't very explicit in showing access modifiers (public, protected, etc.. keywords) when new classes in Visual Studio are created. So, take good care and think about the accessibility of your class because it's the door to your implementation internals.


Reposting the awesome diagrams from this answer.

Here are all access modifiers in Venn diagrams, from more limiting to more promiscuous:

private:
enter image description here

private protected: - added in C# 7.2
enter image description here

internal:
enter image description here

protected:
enter image description here

protected internal:
enter image description here

public:
enter image description here


public - can be access by anyone anywhere.
private - can only be accessed from with in the class it is a part of.
protected - can only be accessed from with in the class or any object that inherits off of the class.

Nothing is like null but in VB.
Static means you have one instance of that object, method for every instance of that class.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to access-modifiers

What is the default access modifier in Java? What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers? Internal vs. Private Access Modifiers Class is inaccessible due to its protection level What are the default access modifiers in C#? What is the equivalent of Java's final in C#? What are public, private and protected in object oriented programming? In C#, what is the difference between public, private, protected, and having no access modifier? What is the difference between 'protected' and 'protected internal'? What is the difference between public, protected, package-private and private in Java?