0

How to use protected function of base class in derived class?

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    A obj = new A();
    obj.Test(); // error thrown;
  }
}

When i tried to use the Test function of base class. It is throwing error..

1

6 Answers 6

2

You can call the Test() method directly without having to create a new object of the base type:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    Test();  // Calls the test method in the base implementation of the CURRENT B object
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

I think one could do it through a protected static method in the base class, without losing the encapsulation.

public class A
{
  protected void Test() { /* ... */ }

  protected static void Test(A obj)
  {
    obj.Test();
  }
}

public class B : A
{
  public void Test2()
  {
    A obj = new A();
    A.Test(obj);
  }
}

Effectively A.Test() can be called only from derived classes and their siblings.

A snippet for testing: http://volatileread.com/utilitylibrary/snippetcompiler?id=37293

Comments

1

That's because 'A's Test() is protected, which means, B sees it as private.

The fact that B inherits from A, and that A contains Test which is protected, doesn't mean that other objects can access Test, even though they inherit from that class.

Although:

Since B inherits from A, B contains the private method Test(). so, B can access it's own Test function, but that doesn't mean B can access As Test function.

So:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    this.Test(); // Will work!
  }
}

Comments

1

Test is protected within an instance of object A.

Just call

this.Test()

No need to create the object A within B.

Comments

1

Seems you misunderstood the word "protected". Have a look at msdn: http://msdn.microsoft.com/en-us/library/bcd5672a(v=vs.71).aspx

Your example needs to be like this:

public class A
{
  protected void Test()
  {
      // some code....
  }
}

public class B : A
{
  public void Test2()
  {
    this.Test();
  }
}

Comments

0

Protected methods are only available to derived types. In other words you are trying to access the method publicly when you create an instance of A.

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.