C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Security in lambdas

Chapter 9: Lambda expressions and expression trees: 9.2.2

Created: 3/3/2008
Last updated: 3/3/2008

Eric raised an interesting point which I not only hadn't covered - I hadn't even thought about it.

A lambda converted to a delegate becomes a method on the class in question (or a nested child class). If the delegate accesses a private field on the class, that's OK because the code all lives in the class.

What happens when a lambda is converted to an expression tree and it accesses a private? We want that scenario to still work, even though when you compile the expression tree, the resulting method is NOT on any method associated with the class.

In the desktop CLR, what we do is rely upon a new feature called Restricted Skip Visibility, whereby partially or fully trusted code is allowed to view the private state of other code provided that the viewing code is at least as or more trusted than the code that owns the private state.

Note that hoisted locals are considered private state.

The implications here are interesting, and things get odder in Silverlight (which doesn't have Restricted Skip Visibility) and in the SQL Server version of the CLR, which doesn't grant the required permission to any code. However, there's good news:

We are presently attempting to design a more general mechanism into all versions of the CLR so that this notion of "this object possesses a license to mess with the private state of that object" is cleanly represented.