What is the difference between public, private, protected, and having no access modifier in C#?

In C#, access modifiers are like invisible guardians that control who can see and interact with different parts of your code. Think of them as security guards for your program.

Public

  • What it is: Public is like shouting from the mountaintop! It means that anyone, anywhere in your code, can access the thing (like a variable or a method) with this modifier.
  • Example:
    public class PublicExample
    {
        public int PublicVariable = 10;
    
        public void PublicMethod()
        {
            Console.WriteLine("This method is accessible by everyone!");
        }
    }
    

Private

  • What it is: Private is like having a secret password to access something. Only the code inside the same class can use or see the thing with a private modifier.
  • Example:
    public class PrivateExample
    {
        private int secretNumber = 42;
    
        private void PrivateMethod()
        {
            Console.WriteLine("This method is a secret!");
        }
    }
    

Protected

  • What it is: Protected is like sharing with family. It allows the thing to be seen and used not only by its own class but also by any class that inherits from it.
  • Example:
    public class BaseClass
    {
        protected int protectedVariable = 100;
    
        protected void ProtectedMethod()
        {
            Console.WriteLine("This method is accessible by family (inheritors)!");
        }
    }
    
    public class InheritedClass : BaseClass
    {
        public void UseProtectedMember()
        {
            Console.WriteLine($"Accessing protected variable: {protectedVariable}");
            ProtectedMethod();
        }
    }
    

No Access Modifier (Internal)

  • What it is: When you don't specify any modifier, the default is like having a "Members Only" sign at the door. Only code within the same project (folder) can access the thing.
  • Example:
    class InternalExample
    {
        internal string internalVariable = "Accessible within the same project";
    
        internal void InternalMethod()
        {
            Console.WriteLine("This method is for members only!");
        }
    }
    

Summary

  • Public: Everyone can access.
  • Private: Only the class itself can access.
  • Protected: Accessible by the class and its "family" (inheritors).
  • No Access Modifier (Internal): Only accessible within the same project.

Understanding these modifiers helps you control who can use and see the different parts of your code, creating a well-organized and secure program.

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice