I’ve got a base class from an outside library that I can’t modify – here’s the relevant piece:
public class BaseClass
{
List<string> _values;
public Values { get { return _values; } }
}
I am inheriting the BaseClass, and I want to set _values to a class that inherits from List(T) in the constructor:
public InheritingClass : BaseClass
{
public InheritingClass():base()
{
//set base._values = new InhertingList<string>(); ?
}
}
What’s the best way to set base._values there? Is there a way to find what private variable is fetched by Values and set that in case the private variable is renamed in the future?
There are other ways I can accomplish what I need to do, but if I could do the following, it would be quicker by far than any ways of achieving my goal without setting the private property value.
Keeping it private, by definition, is meant to prevent this exact scenario.
The best option would be to implement a protected setter:
This way, your InheritingClass has access to the setter, and can do:
But since you can’t change the base class, it is, technically, possible to do this via reflection (in a full trust scenario). I don’t recommend this approach, though:
The danger of doing what you are attempting, btw, is that you’re going to change the implementation defined by the BaseClass to something that you’re providing. It’s very easy to introduce subtle bugs, since you’re (purposefully) “breaking” the implementation details in the base class.
I’d try to rethink your algorithm, and see if there’s another way around this issue.