Alex Rivera | Logout

C# to C#, convenience language features

Asked 2010-01-09T21:43:31.427
11

I'd like to learn what are all the convenience features of C#, and how they map to C#.

For example, automatic properties:

public string Foo { get; set; }

...maps to something like this:

string <Foo>k__BackingField;

[CompilerGenerated]
public string Foo {
   get { return this.<Foo>k__BackingField; } 
   set { this.<Foo>k__BackingField = value; } 
}

Foreach loops:

foreach(char c in "Hello") {
   Console.WriteLine(c);
}

...maps to something like this (I think):

CharEnumerator en;

try {

   en = "Hello".GetEnumerator();

   while (en.MoveNext()) {
      char c = en.Current;

      Console.WriteLine(c);
   }

} finally {

   IDisposable disp = en as IDisposable;

   if (disp != null)
      disp.Dispose();
}

The disposing of the enumerator makes foreach very useful when dealing with unmanaged resources, like looping through lines in a file, or records in a database.

I think a good understanding of these high level features can help us write better code. What are other convenience features of C#, and how do they map to C#?

Edit
Report

2 Answers

6

LINQ as a whole (especially using the LINQ query syntax) is essentially a major C#/.NET convenience feature that replaces for-loops/iterators/complex query logic much of the time.

answered 2010-01-09T22:04:26.070
3

Anonymous delegates get changed into methods during compilation, so this:

var collection = new[] { 1, 2, 3, 4 }.Where(i => i == 2);

causes a new method to be created:

[CompilerGenerated]
private static bool <Main>b__0(int i)
{
    return (i == 2);
}

and changes to:

IEnumerable<int> collection = new int[] { 1, 2, 3, 4 }.Where<int>(<Main>b__0);

Notice that it uses a method name that you cannot create before compiling <Main>b__0 - you cannot have <> in a method name, so it always avoid collisions.

The same process happens to this as well as i => i == 2:

delegate(int i) { return i == 2; }

You will also notice that you can use short hand for:

new[] { 1, 2, 3, 4 }
// goes to...
new int[] { 1, 2, 3, 4 }

and

var foo = new Foo();
// goes to...
Foo foo = new Foo();
answered 2010-01-09T23:46:04.660

Your Answer