Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# anonymous backing fields with non-auto properties

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.

like image 488
Bryan Hart Avatar asked Aug 05 '11 03:08

Bryan Hart


2 Answers

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.

like image 139
Anthony Pegram Avatar answered Oct 02 '22 00:10

Anthony Pegram


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.

like image 45
Adrian Iftode Avatar answered Oct 02 '22 00:10

Adrian Iftode