I want to make a private member variable that is private even to the class that owns it, and can ONLY be accessed by its getters and setters. I know you can do this with auto-properties like
private int MyInt{ get; set;}
But I want to be able to modify the getter and setter so (for example) I could log how many times the field has been set (even by the owning class). Something like this
private int MyInt
{
get{ return hiddenValue; }
set{ hiddenValue = value; Console.Out.WriteLine("MyInt has been set");}
}
where "hiddenValue" is the member that is only accessible in the getter and setter. Why? because I'm a paranoid defensive programmer, I don't even trust myself :p.
Is this possible in C#? and if so, what is the syntax?
Thanks.
You really should trust yourself.
And no, you can't make a variable so private even the encapsulating class can't see it.
If you really want this, you could encapsulate the value in a nested class, which would be able to cover its own privates.
class Foo
{
class Bar // nested
{
private int _value;
public int Value
{
get { return _value; }
set { _value = value; /* logic */ }
}
}
}
Foo can instantiate a Bar, get at bar.Value, but it cannot get to _value.
Is not possible with any language in .Net. And is good. Defensive coding is good, but when becomes paranoid, it makes go crazy other developers who need to maintain it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With