0

I have the below scenario:

 public class T1
    {
        protected virtual int add()
        {
            return 1;
        }
    }

    public class T2 : T1
    {       
    }

    public class T3 : T2
    {
        protected override int add()
        {
            return 3;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            T1 t1 = new T3();            

            ((T3)t1).add();

        }
    }

however, in the line that call to add function ((T3)t1).add(); i am get error T3.add() is inaccessible due to its protection level

1
  • 1
    You could call protected method only inside of the class or derived class, but you try to call it from outside of the class. Commented Feb 23, 2017 at 13:44

1 Answer 1

1

From MSDN

The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances.

You can't access protected method from another class. It need to be public.

public class T1
{
    public virtual int add()
    {
        return 1;
    }
}

public class T2 : T1
{       
}

public class T3 : T2
{
    public override int add()
    {
        return 3;
    }
}

class Program
{
    static void Main(string[] args)
    {
        T1 t1 = new T3();            

        ((T3)t1).add();

    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.