| Lambda Expressions, Type Inference, and Anonymous Types |
|
|
| Friday, 08 June 2007 19:17 | |
|
I mentioned type inference in a previous post, but I don't think I mentioned lambda expressions, which is a new feature of C# 3.0. The lambda operator, btw, is "=>". Lambda expressions provide a cleaner way to do anonymous methods. In fact, lamba expressions area actually converted to delegates and compile to the same IL code. so this... delegate( int val ) { return val * val; }; is essentially equivalent to this... With type inference, the type of a local variable is inferred from the expression used to define it. Use the "var" keyword. For example... int i = 42;
string[] ss = new string[] { "Hello", "world" };
Dictionary<Person, List<Student>> people = (some expression); are equivalent to... var i = 42;
var ss = new string[] { "Hello", "world" };
var people = (some expression); You can also create an anonymous type on the fly... something like this: Person p = bll.People.Get(42);
var anonType = new { First = p.FirstName, Last = p.LastName };</p> <p>Console.WriteLine ( "{0} {1}", anonType.First, anonType.Last );
|

