We have a very vital role of Access modifier in C#, there are five different types which are as follows,
- Public
Whenever you have to make your member/variables, methods, or properties available 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 has 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 is to only this class, it cannot be accessible outside class, nor can you inherit, neither can you create an object of that class. For example - You went to buy ice-cream in an ice-cream parlour, you will get this only inside the ice cream parlour, if you want it outside that parlour you won't buy it.
- Private class IceCreamParlour
- {
- private string buttorChoclate;
- }
- public class IceCream
- {
- public static void Main()
- {
-
- 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 won't achieve it.
- Internal
It is accessible only to single assembly/Project, you cannot access member of internal one outside that assembly.
- Protected Internal
It's a combination of Protected and Internal, it is accessible to your derived class and only accessible to your assembly/Project.