Category Archives: Uncategorized

So how about truly private fields in C#?

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.

Truly private fields in JavaScript

So I was chatting with Christian Blunden about JavaScript, and he asked if it was possible to have private fields in JavaScript.

Now the language doesn’t have a key word but I knew that you could use function scoping to achieve the same affect as I had seen the same thing done using the E programming language.

So after 5 minutes here is what we came up with:

function Purse(money) {
	this.getMoney = function() {
		return money;
	}
	this.setMoney = function(newMoney) {
		money = newMoney;
	}
}

This will create a truely private field that can only be accessed via the methods.

You can still mix your private getters and setters with prototype methods. eg:

Purse.prototype = {
	add : function( money ) {
		this.setMoney(this.getMoney() + money);
	}
}

var p = new Purse(2);
p.add( 1 );
p.getMoney(); returns 3

If you tried to access the money field directly it would be undefined.