Can you modify a private field of a super class? - c#

I'm working with a closed-source base class. Can I somehow change a private field in the base class from my inheriting class?
Assuming the following class structure:
public class Parent
{
private bool age;
}
public class Baby : Parent
{
public bool newAge{
get {
return age;
}
}
}
This currently gives you a compile-time error:
'Parent.age' is inaccessible due to its protection level.
How do you access the field "age" from the Baby class? Can you use reflection or something similar?

You could, using reflection. It looks like this:
public class Baby : Parent
{
private readonly FieldInfo _ageField = typeof(Parent).GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
public int newAge
{
get
{
return (int)_ageField.GetValue(this);
}
set
{
_ageField.SetValue(this, value);
}
}
}
If it's provided by a 3rd party, there is nothing stopping them from changing it, renaming it, it removing it all together. That's one of the points of private. Keep in mind that it might be private for a reason. Tinkering where you aren't suppose to can lead to unexpected results.

You can try to use reflection to get access to private fields and modify them. Like:
typeof(Parent)
.GetField("age", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(parent, 14);
where parent is an instance of Parent.

You can modify those values via reflection. That being said, you probably shouldn't.
Private fields, properties, and methods are all things that are not explicitly guaranteed by the contract of the class. If this 3rd-party API is reliable the public contracts they provide will not change (but they can easily grow).
The private and internal parts are not guaranteed to be the same from release to release. By coupling your code to those parts of the code, you've introduced a lot of risk to your future releases. If you're ok with that risk (and it's well-documented as to why you're doing it), the by all means, reflect away.
If you do go that route, I would recommend an Adapter class that all your consuming code uses instead of this 3rd-party API. With the Adapter pattern, only the one class will need to change in response to the 3rd-part API changes.

Well, since you cannot change the source code of the parent class, there's possibly 2 choices:
If the parent class is a partial class, you can define your own contribution (another Parent class) defining a public Property (it can access private fields).
You can indeed use reflection.

No you cannot do it. Unless you use reflection for example:
Reflection.FieldInfo fields[] =
myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

Related

Is it possible to declare a field somehow local to its property [duplicate]

I'm using .NET 2.0 so do not have access to automatic properties. So I must resort to the following way of coding private variables and public properties
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
For methods of the containing class of the above private/public members, is there anyway to restrict access to the private variable? I do not like that I can either use m_hello or Hello.
Thanks.
As others have suggested this should be an answer...
You can still use automatic properties in C# 3 when targeting .NET 2.0, along with quite a few other C# 3 features. Unlike (say) expression trees, automatic properties don't need anything special from the CLR or the framework, beyond the [CompilerGenerated] attribute (which was introduced in .NET 2.0).
So if you're using VS2008 or VS2010, then it would be worth using an automatic property.
For what it's worth though, I'd like this ability too. I'd like to be able to scope variables within a property:
public string Name
{
private string name;
get { return name; }
set { name = value; }
}
I view this a bit like making a private variable readonly - it makes no difference to clients, but it helps to enforce correctness within the class code itself.
You can accomplish this via inheritance:
abstract class A // A is not instantiatable due to being abstract
{
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
}
class B : A
{
// B now cannot access the private variable, use B in your code instead of A
}
I am not claiming that this is good. Just that it can be done.
No there is not a way to do that, other than to simply follow your own convention and do this.Hello if you really need to go through your public property.
I don't see why you would need/want to do this either, as since it is your internal class, you are the one in control of the code and you can define what/how it is used, so there shouldn't be an issue.
No. Any method inside the class will have access to both.
Your team should standardize on which to use (Property or private variable).
Once you decide which to use, you could try to use a custom FxCop rule to enforce the standard.
No, basically. Well, you could do something with compiler warnings via [Obsolete] and #pragma, but that would be excessive.
You could probably do it with tooling, but eventually you need to trust people not to do stupid things. After all, do you have special rules about:
while(true) { }
or do you just put that down to "don't be stupid"? ;p
You should only access the property through the public Hello property. This is the reason for this pattern. If you add any functionality to the get or set, if you are accessing the private instance, you will introduce bugs into your code. But the anwer is NO, you cannot prevent someone from calling the Private when they are inside your class changing your code.
Personally, I see nothing wrong with accessing the private member within the class. In fact that's what I typically do (unless there's logic within the property getter/setter that I always want to leverage).
It just makes sense to me: the code within the class constitutes that class's implementation; why hide an implementation from itself?
Here's an example of what I mean. Suppose I have some member, m_denominator, and I want it never to be zero:
private int m_denominator = 1;
public int Denominator
{
get { return m_denominator; }
set
{
if (value == 0)
throw new ArgumentException("Denominator must not be zero.");
m_denominator = value;
}
}
I might say to myself: "OK, everywhere I set this value within this class, I should use Denominator to make sure I'm not setting it to zero." But I'm completely in control of what I'm setting Denominator to -- I'm inside the class! In this scenario, the point of the logic in the Denominator property is to protect the class from invalid values set by client code. There's no excuse for setting your internal state to some invalid value within the implementation of a class itself.
Of course this is not an absolute rule. There are surely times when using the property for its logic within a class may be a sensible choice as a protective measure; really, I'm just arguing that it's not wrong to access private members from within a class.
If you find yourself wanting to hide details from yourself, that may be a code smell that your class has too many responsibilities. Consider extracting one of the responsibilities into a new class.
I believe in C#10, or at least a proposal for it, you can use semi-auto properties.
We can now use the field keyword in place of a backing property field.
So this:
private int _theNumber;
public int TheNumber
{
get => _theNumber;
set => _theNumber = value;
}
Becomes this:
public int TheNumber
{
get => field;
set => field = value;
}
Granted in the example I provided an auto property would make more sense, but I wanted to show a simple example.

If we inherit a class do the private variables also get inherited?

If we inherit a class do the private variables also get inherited?
I know that "Yes, the variables are inherited but cannot be accessed directly by the class interface."
What I want to know is how can we access the private variables/methods from the child class
What I am trying to say is that private members are also inherited.But how to access the same without making them protected.
I know that "Yes, the variables are inherited but cannot be accessed directly by the class interface."
So you know the answer then.
What I want to know is how can we access the private variables/methods from the child class
You can’t, that’s why they are private (rather than, say, protected). The whole intention of making them private is so that you cannot access them from anywhere, notably including child classes.
Explicitly breaking this encapsulation is almost always a sign of a broken design and shouldn’t ever be part of a normal code flow. However, there are situations in which you want to reason about some code, and in these situations it may be necessary to examine even private values. Reflection libraries allow this. Here’s a simple example using the System.Reflection capabilities:
class Widget {
private readonly string identifier;
public Widget(string identifier) {
this.identifier = identifier;
}
}
class MainClass {
public static void Main(string[] args) {
var widget = new Widget("my_test_widget");
var type = widget.GetType();
var field = type.GetField("identifier",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
Console.WriteLine($"{field} = {field.GetValue(widget)}");
}
}
Make them protected. For variables, make a protected property that the child classes then use.
You can only access private variables/methods from a derived class using reflection. You cannot access them in a "natural" way, since the whole point of making them private is to hide them from other classes (including derived classes).
Make it protected property instead of private member.
What I want to know is how can we access the private variables/methods from the child class
.........
But how to access the same without making them protected.
You might want to try using reflection:
Here is a similar question / answer that explains how this can be done.

Blocking access to private member variables? Force use of public properties?

I'm using .NET 2.0 so do not have access to automatic properties. So I must resort to the following way of coding private variables and public properties
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
For methods of the containing class of the above private/public members, is there anyway to restrict access to the private variable? I do not like that I can either use m_hello or Hello.
Thanks.
As others have suggested this should be an answer...
You can still use automatic properties in C# 3 when targeting .NET 2.0, along with quite a few other C# 3 features. Unlike (say) expression trees, automatic properties don't need anything special from the CLR or the framework, beyond the [CompilerGenerated] attribute (which was introduced in .NET 2.0).
So if you're using VS2008 or VS2010, then it would be worth using an automatic property.
For what it's worth though, I'd like this ability too. I'd like to be able to scope variables within a property:
public string Name
{
private string name;
get { return name; }
set { name = value; }
}
I view this a bit like making a private variable readonly - it makes no difference to clients, but it helps to enforce correctness within the class code itself.
You can accomplish this via inheritance:
abstract class A // A is not instantiatable due to being abstract
{
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
}
class B : A
{
// B now cannot access the private variable, use B in your code instead of A
}
I am not claiming that this is good. Just that it can be done.
No there is not a way to do that, other than to simply follow your own convention and do this.Hello if you really need to go through your public property.
I don't see why you would need/want to do this either, as since it is your internal class, you are the one in control of the code and you can define what/how it is used, so there shouldn't be an issue.
No. Any method inside the class will have access to both.
Your team should standardize on which to use (Property or private variable).
Once you decide which to use, you could try to use a custom FxCop rule to enforce the standard.
No, basically. Well, you could do something with compiler warnings via [Obsolete] and #pragma, but that would be excessive.
You could probably do it with tooling, but eventually you need to trust people not to do stupid things. After all, do you have special rules about:
while(true) { }
or do you just put that down to "don't be stupid"? ;p
You should only access the property through the public Hello property. This is the reason for this pattern. If you add any functionality to the get or set, if you are accessing the private instance, you will introduce bugs into your code. But the anwer is NO, you cannot prevent someone from calling the Private when they are inside your class changing your code.
Personally, I see nothing wrong with accessing the private member within the class. In fact that's what I typically do (unless there's logic within the property getter/setter that I always want to leverage).
It just makes sense to me: the code within the class constitutes that class's implementation; why hide an implementation from itself?
Here's an example of what I mean. Suppose I have some member, m_denominator, and I want it never to be zero:
private int m_denominator = 1;
public int Denominator
{
get { return m_denominator; }
set
{
if (value == 0)
throw new ArgumentException("Denominator must not be zero.");
m_denominator = value;
}
}
I might say to myself: "OK, everywhere I set this value within this class, I should use Denominator to make sure I'm not setting it to zero." But I'm completely in control of what I'm setting Denominator to -- I'm inside the class! In this scenario, the point of the logic in the Denominator property is to protect the class from invalid values set by client code. There's no excuse for setting your internal state to some invalid value within the implementation of a class itself.
Of course this is not an absolute rule. There are surely times when using the property for its logic within a class may be a sensible choice as a protective measure; really, I'm just arguing that it's not wrong to access private members from within a class.
If you find yourself wanting to hide details from yourself, that may be a code smell that your class has too many responsibilities. Consider extracting one of the responsibilities into a new class.
I believe in C#10, or at least a proposal for it, you can use semi-auto properties.
We can now use the field keyword in place of a backing property field.
So this:
private int _theNumber;
public int TheNumber
{
get => _theNumber;
set => _theNumber = value;
}
Becomes this:
public int TheNumber
{
get => field;
set => field = value;
}
Granted in the example I provided an auto property would make more sense, but I wanted to show a simple example.

Is using get set properties of C# considered good practice?

my question is simple, is using the get set properties of C# considered good, better even than writing getter and setter methods? When you use these properties, don't you have to declare your class data members as public ? I ask this because my professor stated that data members should never be declared as public, as it is considered bad practice.
This....
class GetSetExample
{
public int someInt { get; set; }
}
vs This...
class NonGetSetExample
{
private int someInt;
}
Edit:
Thanks to all of you! All of your answers helped me out, and I appropriately up-voted your answers.
This:
class GetSetExample
{
public int someInt { get; set; }
}
is really the same as this:
class GetSetExample
{
private int _someInt;
public int someInt {
get { return _someInt; }
set { _someInt = value; }
}
}
The get; set; syntax is just a convenient shorthand for this that you can use when the getter and setter don't do anything special.
Thus, you are not exposing a public member, you are defining a private member and providing get/set methods to access it.
Yes, members should normally never be declared public in good design for several reasons. Think about OOP where you inherit the class later. Kind of hard to override a field. :-) Also it prevents you from keeping your internals from being accessed directly.
The simplistic get; set; design was introduced in C# 2.0. It's basically the same as declaring everything with a private member backing it (decompile it out in tool like Reflector and see).
public int someInt{get;set;}
is directly equal to
private int m_someInt;
public int someInt{
get { return m_someInt; }
set { m_someInt = value; }
}
The great part about having the simplified getter/setter is that when you want to fill in the implementation with a little bit more guts later, you do not break ABI compatibility.
Don't worry about getter/setters slowing down your code through indirection. The JIT has a thing called inlineing makes using the getter/setter just as efficient as direct field access.
Yes. Data members should be private and automatic properties allow it and give public access on right way.
But you should be careful. Understand the context is very important. In threaded application, update one property following an another related property can be harmful to consistency. In that case, a setter method updating the two private data members in a proper way makes more sense.
In your first example C# automatically generates the private backing fields so technically the data member is not declared as public only the getter/setter.
because with public data member , that data member can be changed or can be read out of class
and you cannot control read/write operation accessibility but with properties you can control
read/write stream for example consider this statement :
public MyVar{private get; public set;}
means value of MyVar can be changed only inside of class and can be read out of class(read privately and read publicly) and this is not possible with just public data members
In a "pure" object oriented approach, it is not considered OK to expose the state of your objects at all, and this appliese to properties as they are implemented in .NET and get_ set_ properteis of Java/EJB. The idea is that by exposing the state of your object, you are creating external dependencies to the internal data representation of your object. A pure object design reduces all interactions to messages with parameters.
Back to the real world: if you try to implement such a strict theoretical approach on the job, you will either be laughed out of the office or beaten to a pulp. Properties are immensely popular because they are a reasonable compromise between a pure object design and fully exposed private data.
It's quite reasonable, and your professor (without context) is wrong. But anyway, using "automatic properties", is fine, and you can do it whether they are public or private.
Though in my experience, whenever I use one, I almost inevitably end up needing to write some logic in there, and hence can't use the auto props.
your professor was quite right.
Consider this trivial example of why "getters" should be avoided: There may be 1,000 calls to a getX() method in your program, and every one of those calls assumes that the return value is a particular type. The return value of getX() may be sotred in a local variable, for example, and the variable type must match the return-value type. If you need to change the way that the object is implemented in such a way that the type of X changes, you're in deep trouble. If X used to be an int, but now has to be a long, you'll now get 1,000 compile errors. If you fix the problem incorrectly by casting the return value to int, the code will compile cleanly but won't work. (The return value may be truncated.) You have to modify the code surrounding every one of those 1,000 calls to compensate for the change. I, at least, don't want to do that much work.
Holub On Patterns

Reflection optimizations with attributes .

Is there a way in C# to:
Get all the properties of a class that have attributes on them (versus having to loop through all properties and then check if attribute exists.
If i want all Public, Internal, and Protected properties but NOT private properties, i can't find a way of doing that. I can only do this:
PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
Is there a way to avoid getting private properties but do get everything else.
Regarding caching: if you access properties via TypeDescriptor.GetProperties then you get caching for free. The TypeDescriptor class has some other nice utility methods for reflection situations like this. It only operates on public properties though (no protected or internal members, and no fields).
There isn't really a way to do it any quicker - but what you can do is do it less often by caching the data. A generic utility class can be a handy way of doing this, for example:
static class PropertyCache<T>
{
private static SomeCacheType cache;
public static SomeCacheType Cache
{
get
{
if (cache == null) Build();
return cache;
}
}
static void Build()
{
/// populate "cache"
}
}
Then your PropertyCache.Cache has the data just for Foo, etc - with lazy population. You could also use a static constructor if you prefer.
I don't believe there's a way to do either of these.
Just how many types do you have to reflect over, though? Is it really a bottleneck? Are you able to cache the results to avoid having to do it more than once per type?
In response to (2): If you're outside of the class/assembly in question, internal and protected are the same as private.
If you want to access these, you'll need to ask for all properties, as you've already done, and filter the list yourself.

Categories