I want to access protected member in a class. Is there a simple way?
-
7Most of the time, it's protected for a reason... – Mehrdad Afshari Dec 02 '10 at 03:01
-
What is the relationship between the class where you access it to the class with the protected member? – MerickOWA Dec 02 '10 at 03:02
-
3@Mehrdad Afshari: And when it isn't than we have to hack through it right? :) Bad designs are sometimes beyond our control. – the_drow Dec 02 '10 at 03:04
4 Answers
There are two ways:
- Create a sub-class of the class whose protected members you want to access.
- Use reflection.
#1 only works if you control who creates the instances of the class. If an already-constructed instance is being handed to you, then #2 is the only viable solution.
Personally, I'd make sure I've exhausted all other possible mechanisms of implementing your feature before resorting to reflection, though.

- 71,468
- 13
- 145
- 180
I have sometimes needed to do exactly this. When using WinForms there are values inside the system classes that you would like to access but cannot because they are private. To get around this I use reflection to get access to them. For example...
// Example of a class with internal private field
public class ExampleClass
{
private int example;
}
private static FieldInfo _fiExample;
private int GrabExampleValue(ExampleClass instance)
{
// Only need to cache reflection info the first time needed
if (_fiExample == null)
{
// Cache field info about the internal 'example' private field
_fiExample = typeof(ExampleClass).GetField("example", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
}
// Grab the internal property
return (int)_fiExample.GetValue(instance);
}

- 22,580
- 14
- 83
- 137
If you can derive from the class that has that protected member than you can access it.
As for using reflection, this might help.
Have you chosen the right accessor for your member?
- protected (C# Reference);
- public (C# Reference);
- private (C# Reference);
- internal (C# Reference).
- You may also combine internal with protected.
By all means, the protected accessor specifies that a member shall be accessed only within a derived class. So, if your objective is to access it outside of a derived class, perhaps should you rather consider using the public or internal accessor!?
Besides, that is doable throught Reflection (C# and Visual Basic).
On the other hand, if you really want to expose the protected members of a class, I would try using public members and returning a reference to the protected through it.
But please, ask yourself whether your design is good before exposing protected members. It looks to me like a design smell.

- 23,773
- 22
- 96
- 162