Tuesday, June 4, 2019

C# : Protected Members



Protected is a keyword in C#, used to define accessibility for class members like variables, properties and methods, etc.
protected members have similar accessibility as private member with only one difference that are also available in derived classes.

Note: for a class that is defining protected member and it's derived classes, they are available as private i.e. class defining protected member and it's derived classes are not able to access protected member via it's object, while any other public or protected member can use that newly defined protected members. please see below example:

class BaseClass
    {
        protected int Add(int a ,int b)
        {
            return a + b;
        }
        protected void AddWrapper()
        {
           Console.WriteLine( Add(5, 9));
        }
  }
  
class DerivedClass : BaseClass
    {
        public void m1()
        {
            int k = Add(4, 5);
            Console.WriteLine("Calling BaseClass's protected methods via Wrapper method m1()");
            AddWrapper();
        }
}

public class Tester
    {
        public static void Main()
        {
            BaseClass obj1 = new BaseClass();
            // not able to call Add method via BaseClass object.
            DerivedClass obj2 = new DerivedClass();
            obj2.m1();
            Console.Read();

        }
}




No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...