In this tutorial you will learn what is access modifier in C#, What are the different type of access modifiers in c# programming! how to use them!
Primarily there are four types of access modifiers in C#, like public, private, protected and internal.
indicate the accessibility is limited only inside the classes / structure
indicates, it can be accessed from anywhere that means there is no restriction on accessibility
Indicates the accessibility is limited within the class and any class :Inherited from this class
Internal access modifiers indicate that Access is limited exclusively to classes defined within the current project assembly
Access is limited to the current assembly and types derived
Now let's experiment how above access modifiers in C# works
We have created following class with five different properties with different modifiers, will test them one by one
class ModifierKeywordSample { public string WTRPublic { get; set; } private string WTRPrivate { get; set; } protected string WTRProtected { get; set; } internal string WTRInternal { get; set; } protected internal string WTRProtectedInternal { get; set; } }
Test 1: Here is the test result of private access modifier ,
If you notice, we can’t see the private member in image below
Test 2: test result of protected access modifier , we can’t see the private protected in image below
Note: in earlier example protected member was appearing, because "ModifierKeywordSample" class was inherited
Test 3: test result of internal access modifier , we can’t see the internal protected in image below
Now to test “Internal” we have created a new application and then added the reference of earlier application, then inherited from “ModifierKeywordSample” which is in other assembly
Test 4: test result of protected internal modifier, Now instead of inheriting from "ModifierKeywordSample" class, if we create a new instance of same "ModifierKeywordSample" , we can't see protected internal member anymore.
Now you can create readonly member in C# class, note: this features is not available in C# 7.1, you must upgrade your C# version 8 or above, however, you can have readonly variable in C# 7.1
public class MyClass { public readonly string Message = "Default Message"; public readonly string Caption { get; set; } = "My Caption"; }
If you want to create overridable member, then you must declare the member with virtual keyword
public class MyClass { public virtual int MaxNumber { get; set; } }
Remember, abstract member of any abstract class is also overridable.
Hope you are enjoying C# Programming
To understand access modifier in c# programming you should read following tutorials