Swathi
Swathi

Reputation: 157

How Can a private member Accessable in Derived Class in C#?

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

Upvotes: 4

Views: 4023

Answers (5)

locka
locka

Reputation: 6029

With reflection:

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503469

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

Upvotes: 4

madcapnmckay
madcapnmckay

Reputation: 15984

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

Upvotes: 2

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391664

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.

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

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.

Upvotes: 5

Related Questions