Jagz S
Jagz S

Reputation: 907

Cannot Access Protected Function in Derived Class in C#?

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..

Upvotes: 0

Views: 3563

Answers (6)

Albus Dumbledore
Albus Dumbledore

Reputation: 12616

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

Upvotes: 2

walther
walther

Reputation: 13600

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();
  }
}

Upvotes: 1

user434817
user434817

Reputation:

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
  }
}

Upvotes: 2

devdigital
devdigital

Reputation: 34349

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.

Upvotes: 0

Totero
Totero

Reputation: 2574

Test is protected within an instance of object A.

Just call

this.Test()

No need to create the object A within B.

Upvotes: 1

Shai
Shai

Reputation: 25619

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!
  }
}

Upvotes: 1

Related Questions