4

How Can BaseClass Private function be Accessible into DerivedClass in C#?

1
  • create public property to access private field in base class Commented Aug 20, 2010 at 8:26

5 Answers 5

11

Either:

  1. Elevate its access from private to protected
  2. or, add another protected member that accesses it, and use this instead from the derived class
  3. or, use reflection
  4. or, change the code so you don't need to access it

Of the 4, I would chose 1 if it's a private property or method, and 2 if it's a private field. I would add a protected property around the field.

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

Comments

5

It can't. That's the whole purpose of the private access modifier:

The type or member can be accessed only by code in the same class or struct.

Of course you could always use reflection.

1 Comment

+1. If you are able to alter the base class, this is what the protected access modifier is for
4

This answer is for completeness only. In almost all cases, use the suggestions in the other answers.

The other answers are all correct, except there's one situation in which a derived class can access a private member in the base class: when the derived class is a nested type of the base class. This can actually be a useful feature for mimicking Java enums in C#. Sample code (not of Java enums, just the "accessing a private member" bit.)

public class Parent
{
    private void PrivateMethod()
    {
    }

    class Child : Parent
    {
        public void Foo()
        {
            PrivateMethod();
        }
    }
}

1 Comment

@Swathi: Well the code I've posted compiles with no problems, so I don't know what the problem is. Please give more detail. ("It's not working" is almost never a helpful thing to say on its own. The obvious followup question is "In what way is it not working?")
3

With reflection:

FieldInfo f = typeof(Foo).GetField("someField", BindingFlags.Instance | BindingFlags.NonPublic);
fd.SetValue(obj, "New value");

Comments

2

It can't. If you want the method to be accessible to derived classes then you need to make it protected instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.