Search code examples
c#inheritancereflectionextension-methodsencapsulation

Invoking protected method in C# - reflection or separate derived class?


I have recently found myself in need of calling a protected method from outside of the class (short reason why: I needed to stop the object from firing OnValueChanged event when its value was changed and this was only possible via its protected Set(value, sendCallback) function).

In the end I came up with two solutions:

1.) create a derived class, and only add this function:

public void SetValue (float val, bool callback) { Set(val, callback); }

Luckily, the class was set as inheritable, so it worked.

2.) Use reflection and extension methods and do this:

public static void SetValue(this Slider slider, float val, bool callback)
    {
        MethodInfo sliderSetMethod = slider.GetType().GetMethod("Set", BindingFlags.NonPublic | BindingFlags.Instance);
        sliderSetMethod.Invoke(slider, new object[] { val, callback });
    }

This worked fine as well. Is there any reason why I should use one or another? Both of them are working fine for now, but they are obviously not really clean solutions, so I would like to know if any of them could cause problems in the future.


Solution

  • I'd say you should use the derived class because that's what protected methods are intended to be used for, and any changes will be caught by the compiler.

    Using reflection to do something the original author didn't intend seems like it could leave you open to other unintended consequences.