PDC Day 2 - Part II

I attended a great session on C#. Talking about Lambda Expressions, Extension Methods, Object Initializers, Anonymous Types, and Query Expressions. Here are a couple things explained, the others would be way more work then I can handle. We went to Universal Studios last night you know. It was a long and busy day. Which is why I am posting this today.

var

You can use var so you don't have to keep telling the compiler what type the object is.

Instead of...                     You can do...
int i = 5;                        var i = 5;
float j = 1.0;                    var j = 1.0;
string name = “Dave”;             var name = “Dave”;
Customer cust = new Customer();   var cust = new Customer();

Object Initializers

You can initialize the properties of a class when you instantiate it.

Customer cust = new Customer { Fname = “Dave“, Lname = “Lloyd“} ;

The compiler turns it into this.

Customer cust = new Customer();
cust.Fname = “Dave“;
cust.Lname = “Lloyd“;

You can nest this to initialize the properties of a class inside another class. So if Customer instantiated two PhoneNumber classes you could do this.

Customer cust = new Customer { 
    OfficePhone = { Area = “905“, Number = “555-1234” }, 
    MobilePhone = { Area = “905“, Number = “555-4321” }};

You can initialize a collection also this way.

 List primes = new List { 2, 3, 5, 7, 11 };

Extension Methods

An extension method is cool, potentially dangerous, but cool. Think of it kind of like an Extender provider for properties. You can create a static method whose first argument must be this. When the compiler sees one of these it brings it into scope for your class. Intellisense will even add it to the list of methods for your class. 

Take these Extension methods Where and Select if I just add a using to my code for this Namespace these methods will be extended onto my class.

namespace System.Query

    public static class Sequence 
   
        public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) { … } 
        public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source,Func<T, S> selector) { … } 
        … 
    }
}

using System.Query;

var contacts = customers.Where(c => c.State == "WA").Select(c => c.Name);

That is enough for now. I'm going to see up and coming features of VB now.