Skip to main content
Go Search

Ayman El-Hattab's Blog [MVP]

Ayman El-Hattab's Blog
Marwan Tarek's Blog
Mohamed Yehia's Blog

SharePoint 4 Arabs - Online SharePoint Training, Video Tutorials and Webcasts in Arabic > Ayman El-Hattab's Blog [MVP] > Categories
Using Lambda Expressions with RunWithElevatedPrivileges

Elevation of privilege, a feature that was added in WSS 3.0 & MOSS 2007, enables you to programmatically perform actions in code by using an increased level of privilege. The SPSecurity.RunWithElevatedPrivileges method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user.

For some reason, I have never seen a code snippet that uses a lambda expression instead of the anonymous method syntax so I thought of showing you how to save some typing by using Lambda.

Commonly used syntax:

{     // Do things by assuming the permission of the "system account".


Much easier syntax:

{     // Do things by assuming the permission of the "system account".

When I asked the following question on Twitter : “Why do people still use the anonymous method syntax rather than Lambda Expressions with SPSecurity.RunWithElevatedPrivileges() ? #SharePoint”

I got the following answer from Todd Bleeker : “Delegate syntax has been around a lot longer. Lambda is still confusing and even scary for most. <Todd />”

I totally agree with Todd, but guys if you are not comfortable with LINQ and lambda expressions, you should familiarize yourself with them before diving deep into developing SharePoint 2010 solutions.

As you all might know, Now in SharePoint 2010 you can use LINQ syntax to retrieve items from your lists instead of using CAML queries. Microsoft has included a LINQ provider for SharePoint in the Microsoft.SharePoint.Linq namespace, some classes in this namespace are responsible for translating the LINQ Queries to CAML ones which are eventually translated into SQL. You can still write CAML Queries and fetch items in the old ways but LINQ can really make your life easier specially when it comes to joins.

LINQ is Better Than ForEach

Chris Eargle has done a great job comparing LINQ and ForEach loops from the performance and maintainability perspective.

Here is Chris’ conclusion: The vast majority of code I come across that either can be written in LINQ or refactored to LINQ has no noticeable, negative performance impact, but it has a positive impact on maintainability.

Click here to read the full post !