Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a class protected field without modifying original class

Tags:

c#

.net

oop

I am using some 3rd party library that exposes some type (returned by a method).

This type has some protected fields i am interested in, however i am not able to use them since their visibility is protected.

Here is a simplification of the problem:

public class A
    {
        protected object Something;

        public A Load()
        {
            return new A();
        }
    }

    public class ExtendedA : A
    {
        public void DoSomething()
        {
            // Get an instance.
            var a = Load();

            // Access protected fields (doesn't compile).
            a.Something = ....
        }
    }

Is there any easy way to achieve this?

like image 708
lysergic-acid Avatar asked Oct 18 '25 21:10

lysergic-acid


1 Answers

Description

You can access the Field using this.Something because your class is derived from class A.

If you want to create a instance of the class A, not your derived class, you can only access the field using reflection.

Sample using Reflection

public class ExtendedA : A
{
    public void DoSomething()
    {
        // Get an instance.
        var a = Load();

        //get the type of the class
        Type type = a.GetType();
        BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;

        // get the field info
        FieldInfo finfo = type.GetField("Something", bindingFlags);

        // set the value 
        finfo.SetValue(a, "Hello World!");

        // get the value
        object someThingField = finfo.GetValue(a);
    }
}

More Information

  • Accessing Protected Properties and Fields with Reflection
like image 124
dknaack Avatar answered Oct 20 '25 09:10

dknaack