Skip to main content

C# Language Extensions to Support LINQ

On the final day of Devweek this year I attended a full-day workshop on LINQ. It was initially billed as a day of “Entity Framework and LINQ”, but annoying the first bit of the title was dropped at some point before the day! Nonetheless it was a good presentation of what LINQ is, what language extension have been developed to support it, and how it is used in LINQ to Objects, LINQ to XML and LINQ to Entities. The talk was given by Niels Berglund.

In order to support LINQ, a number of amends and enhancements were made to the .Net compiler and the VB.Net and C# languages – I found it worth getting my head around these, so that the LINQ language introduced later appeared less like “magic”.

Automatic Properties

Traditionally properties would be created in a class with a public accessor and a private backing store:

private string mstrFirstName;

public string FirstName
get { return mstrFirstName; }
set { mstrFirstName = value; }

At the compiled code level this hasn’t changed, but in C# as a productivity enhancement you can now simply do this:

public string FirstName { get; set; }

Object Initialisers

Again as an alternate syntax, objects can be initialised in a single statement:

User objUser = new User { ID = 1, FirstName = “Fred”, LastName = “Bloggs” }

Type inference with var

For local types, you can leave the complier to work out what type you are assigning to a variable. Note this is not the same as VB’s variant, or an untyped variable found in an interpreted language like VBScript – it will be typed in the compiled code, and the compiler will complain if you try to subsequently assign a string to a variable initialised with an integer for example.

var i = 1;

Personally, I would only use this when the occasion warranted it – e.g. from LINQ queries – as I feel this reduces code readability.

Extension Methods
Can be used to extend classes that may be sealed or for which you may not have source code available. Really they are just static methods that appear to be instance methods.

e.g. adding an extension method to the string class:

static class MyExtensions
public static string MyExtension(this string s)
return DoSomething(s);
Anonymous Methods
Allow you to define a method in-line. Normally when you use delegates you pass an existing method - using anonymous method you can define it in the same line as the call.

Lambda Expressions
Lambda expressions are another way of writing anonymous methods (inline functions):

Array.Sort (nums, delegate(int a, int b) {return a.CompareTo(b); } );

Array.Sort (nums, {a, b} => a.CompareTo(b) );