Tuesday, 2 June 2020

1000 C# Facts Part-2 : Access Modifiers



Access Modifiers define the accessibility of a class and its members in a program. It allow you to control access to the class and to restrict the class to be instantiated.

There are mainly 5 different access modifiers available in c#.
1. Private
2. Protected
3. Internal
4. Protected Internal
5. Public

#1. Public: The type (i.e class) or it's member can be accessed by any other code which is either present in the same assembly(dll)  or another assembly that references it. 

Public members are available any where without any restrictions.

   // Declaring employee id and name as public 
    public int employeeId; 
    public string employeeName; 
  
    // Constructor 
    public Student(int r, string name) 
    { 
        employeeId = id ; 
        employeeName = n; 
    } 
  
#2. Private: The members which is declared as private are available only with in the containing type.

   // Declaring employee id  as Private.

    private int employeeId; 

// employeeId will not be available in any other classes except current class.

#3. Protected: The members which is declared as protected are available with in the containing type(i.e same class) and  to the types (classes) that derive from the containing type.

class Color{ 
    // Member colorType declared as protected 
    protected int colorType ;
  
    public Color() 
    { 
        colorType = "red"; 
    } 
  
// class Phone inherits the class Color
class Phone  : Color { 
  
    // Members of Phone class can access member of class 'Color' 
    public int getcolorType() 
    { 
        return colorType; 
    } 

#4. Internal: The members which is declared as Internal are available any where within the containing assembly. 

Compile time error will through when we try to access, an internal member from outside the containing assembly.

#5. Protected Internal:  Protected Internal members can be accessed by any code in the assembly in which it is declared or from within a derived class in another assembly.

It is a combination of protected and internal. If you have understood protected and internal, this should be very easy to follow.

Key Facts About Access Modifiers : 

 >  Default access modifier of class is Internal. 
 >  Default access modifier of class member is private. 
 >  Access modifiers are not allowed on static constructors.
  Static keyword is used to access members of class before the object creation of that class.
 >  An object of a derived class cannot access the private member of the base class.
 >  The main()method is declared private by default if no other access specifier is used for it.




Thank You





No comments:

Post a Comment

In case of any query , please let me know, Thanks