Wednesday, January 28, 2009

Protected vs Protected Virtual c# -- The answer's in the code

While the internets have failed me this time (even msdn doesn't mention protected virtual), writing a quick console application saved the day. Consider the following code:

using System;

namespace protected_virtual
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.Method3();
            a.Method4();

            B b = new B();
            b.B_Method1();
            b.Method3();
            b.Method4();

            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
    }

    class A
    {
        protected void Method1()
        {
            Console.WriteLine("A.Method1");
        }

        protected virtual void Method2()
        {
            Console.WriteLine("A.Method2");
        }

        public void Method3()
        {
            Console.WriteLine("A.Method3");
        }

        public virtual void Method4()
        {
            Console.WriteLine("A.Method4");
        }
    }

    class B : A
    {
        public void B_Method1()
        {
            base.Method1();
        }

        protected override void Method2()
        {
            Console.WriteLine("B.Method2");
        }

        public override void Method4()
        {
            Console.WriteLine("B.Method4");
        }
    }
}

 
The code produces the following output:

A.Method3
A.Method4
A.Method1
A.Method3
B.Method4

Press any key to continue...

While this may seem trivial if you analyze the code closer you will discover the answer. First of all you'll notice that in Main Method1 and Method2 cannot be accessed, this is because they are declared as protected. However, Class B can access them because it derives from A. Refer to B_Method1() which is public but accesses the base Method1() from A. Also note that it outputs A.Method1. So my conclusion is that you would use protected if you only want a subclass to access the method. You would use protected virtual if you only want a subclass to access the method but also provide the ability for the subclass to extend or override it. Finally you would use public virtual if you want anyone to access the method but also want to allow a subclass to extend or override it.

2 comments:

  1. What if I want to access to a variable of a protected function by a public function , when both of them are from the same class?

    ReplyDelete