UPDATE: Jim pointed out that you can access the field via reflecting over the delegate.  (See comment) Damn this is a bit like how java does anonymous access to private fields of the parent class. I wonder if you could use this for some nasty security violations as people tend to think local variables are safe from reflection.

After the crazy !@$%  with JavaScript yesterday I said to Christian, I bet we can do this with C# lambda. So the challenge was set….

class Purse
    public Func<int> get;
    public Action<int> set;

    public Purse(int money)
        get = () => { return money; };
        set = (newMoney) => { money = newMoney ; };

And here is the test …

var p = new Purse(2);
p.set(p.get() + 1);
Assert.AreEqual(3, p.get());

If you tried to use reflection, as expected there is no field to inspect.

1 thought on “So how about truly private fields in C#?

  1. var p = new Purse(2);
    p.set(p.get() + 1);

    int money = (int)p.get.Target.GetType().GetField(“money”).GetValue(p.get.Target);

    Assert.AreEqual(3, money);

    Or am I missing the point?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.