C# Access Modifiers

C# Code Snippets Access Modifiers
Share:

About

In this code snippet, we will learn how to use access modifiers in C#.

Access modifiers are used to define the access level of types and members. The following access modifiers are available: public, private, protected, internal, protected internal, private protected. 

  • public members are accessible to everyone.
  • private members are only accessible to code inside their class.
  • protected members can only be accessed from their class or any derived(child) class.
  • internal members can be accessed by any code inside the same assembly.

 Let’s see how to use access modifiers in the code example below.

Code:

using System;

namespace AccessModifiers
{
    class Program
    {
        static void Main(string[] args)
        {
            //Types of access modifiers

            //Public members are accessible to everyone.
            //Private members are only accessible to code inside their class.

            //There are a few more access modifiers such as protected, internal, ...
            //Protected members can only be accessed from their class or any derived(child) class.  
            //Internal members can be accessed by any code inside the same assembly.

            MyClass MC = new MyClass();

            //Can be accessed outside of the class as it's marked as public. 
            MC.MyPublicProperty = 10;

            //Cannot be accessed outside of the class as it's marked as private. 
            //MC.MyPrivateProperty = 10;


            //This method can be accessed ouotside it's class.
            MC.MyPublicMethod();

            //This method can't be accessed outside of it's class. 
            //MC.MyPrivateMethod();


            Console.ReadLine();
        }
    }

    class MyClass
    {
        public int MyPublicProperty { get; set; }
        private int MyPrivateProperty { get; set; }

        public void MyPublicMethod()
        {
            Console.WriteLine("From MyPublicMethod()");
            
            //This method can only be called from inside its class. 
            MyPrivateMethod();
        }

        private void MyPrivateMethod()
        {
            Console.WriteLine("From myPrivateMethod()");
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger