What is Public, Private, Protected, Internal, Protected internal In C#
- 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.- public class HRDept
- {
- public string HR= "Your HR";
- }
- public class Company
- {
- public static void Main()
- {
- Company com = new Company();
- Console.WriteLine("Hello World" + " i am " + com.HR);
- }
- }
- 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.- Private class IceCreamParlour
- {
- private string buttorChoclate;
- }
- public class IceCream
- {
- public static void Main()
- {
- //throw an compile time exception, inaccessible due to its protection level
- IceCreamParlour ice= new IceCreamParlour();
- }
- }
- 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. - Internal
It is accessible only to single assembly/Project, you cannot access member of internal outside that assembly. - 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