Access Modifier in C# - OmIndia

Teach To India

Wednesday, July 05, 2017

Access Modifier in C#


What is Public, Private, Protected, Internal, Protected internal In C#



  1.  Public 
    Whenever you have to make it available your member/variables, methods, properties for your entire application, then you can go with Public as an access modifier. it is visible to all other classes without inhertance, For example - HR of an organization having all access, which means HR is available to any department without any constraint.
    1. public class HRDept  
    2.  {  
    3.    public string HR= "Your HR";  
    4.  }  
    5.   
    6. public class Company  
    7.  {   
    8.    public static void Main()  
    9.   {  
    10.     Company com = new Company();  
    11.     Console.WriteLine("Hello World" + " i am " + com.HR);  
    12.    }  
    13. }  
  2. Private 
    Its access to only his class, it cannot be accessible outside of class, nor you can inherit, neither you can create an object of that class. For example - You went to buy ice-cream in ice-cream parlour, you will get this only inside icecream parlour, if you want outiside that parlour you wont buy it.
    1. Private class IceCreamParlour  
    2. {  
    3.    private string buttorChoclate;  
    4.  }  
    5. public class IceCream  
    6. {   
    7.   public static void Main()  
    8.   {  
    9.     //throw an compile time exception, inaccessible due to its protection level  
    10.     IceCreamParlour ice= new IceCreamParlour();  
    11.     }  
    12. }  
  3. Protected 
    It is accessible outside your class, only to your derived class, if you try to achieve this by creating an object of that class then you wont achieve those.
  4. Internal
    It is accessible only to single assembly/Project, you cannot access member of internal outside that assembly.
  5. Protected Internal 
    Its an combination of Protected and Internal, it is accessible to your derived class and only accessible to your assembly/Project.

No comments:

Post a Comment

Comments

Popular