Mar 10 2010

Object Initializers, delegates, anonymous types, type inference and LINQ

Category: UncategorizedMike Lovell @ 9:04 pm

I thought I’d put together a quick and nasty demo showing the use of object initializers, delegates, anonymous types, type inference and LINQ in one place.

The main reason for the existence of ‘var’ is to support anonymous types (although you’ll notice I use ‘var’ practically everywhere, that’s just my style!).

I can define a new type in my code simply by implying its properties. For example:

   1:    var myType = new
   2:        {
   3:            ParamA = "valuea",
   4:            ParamB = "valueb",
   5:            Number  = 123
   6:        }

The compiler (and the VS.NET environment, as we can use intellisense against it) creates the class definition internally. We can now access the properties of that object, just as if we defined it explicitly:

   1:  Console.WriteLine("{0} {1} {2}", myType.ParamA, myType.ParamB, Number);

Why? Well I guess the most common reason for using anonymous types is to return a subset of data from a LINQ query. This is something we’ll do in the demo.

I like to use the type inference capability of ‘var’ to make my code more (in my mind!) cleaner. For example:

   1:  MyClass classObject = new MyClass();

Can be written as:

   1:  var classObject = new MyClass();

I think the later looks better, it seems kinder of my eyes but it’s a personal preference thing, so don’t follow me on that habit just for the sake of it! :-)

I’m also a heavy user of ‘Object initializers’ rather than constructors. Although when you approach more complex classes there often is a need to control the instantiation of an object more tightly and go with the constructor route. ‘Object initializers’ allow me to write nice readable code because it uses named parameters (note: you can now use named parameters with constructors) and it’s nice to not have to write constructors for simple classes. So my code might look a little like this:

   1:  var classObject = newMyPersonClass()
   2:      {
   3:          FirstName = "Mike",
   4:          LastName = "Lovell"
   5:      };

Delegates and LINQ are pretty vast topics, so I’m not going to attempt to cover them apart from to demonstrate their use in a way that might be helpful, so on to the demo…

First, lets declare a couple of classes to use.  For this we’re going to use a simple class called ‘Person’, and a collection of ‘Person’ (by inheriting List<Person>) called ‘People’

   1:  // Author: Mike Lovell (mike.lovell@gotinker.com)
   2:   
   3:  class Person
   4:  {
   5:      public    stringFirstName = "";
   6:      public    stringLastName = "";
   7:  }
   8:   
   9:   
  10:  class People : List<Person>
  11:  {
  12:  }
  13:  

Now lets define a new instance of our collection and fill it with some test data.  As we haven’t defined any constructors, we’re going to use ‘Object initializers’ to define the values of ‘FirstName’ and ‘LastName’

  14:   
  15:  class Program
  16:  {
  17:      static void Main(string[] args)
  18:      {
  19:          var people = new People();
  20:   
  21:          people.Add(new Person()
  22:              {
  23:                  FirstName    = "Bob",
  24:                  LastName    = "Smith"
  25:              });
  26:   
  27:          people.Add(new Person()
  28:              {
  29:                  FirstName    = "John",
  30:                  LastName    = "Doe"
  31:              });
  32:   
  33:          people.Add(new Person()
  34:              {
  35:                  FirstName    = "Bill",
  36:                  LastName    = "Johnson"
  37:              });
  38:   

Now the delegate, we can use an anonymous delegate to make a rather nifty ‘ForEach’ loop to display the value of each item

  39:          Console.WriteLine("All People:n");
  40:   
  41:          people.ForEach(delegate(Person person)
  42:              {
  43:                  Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
  44:              });
  45:   

Now the LINQ and anonymous type.  We want to find all the instances of ‘Person’ where their first name begins with a ‘b’, then we’re going to create a anonymous type to store their full name in (of course we could just return it to a string array, but this is a contrived example).  We’ll then display the results to ‘Console’IEnumerable<T> does not have a ‘ForEach’ method so I will be using a more conventional ‘for’ loop!

  46:          var bNames    = from i
  47:                          in people
  48:                          where i.FirstName.ToLower().StartsWith("b")
  49:                          select new
  50:                              {
  51:                                  FullName = String.Format("{0} {1}", i.FirstName, i.LastName)
  52:                              };
  53:   
  54:          Console.WriteLine("nFirst names that start with a 'b':n");
  55:   
  56:          foreach (var person in bNames)
  57:          {
  58:              Console.WriteLine(person.FullName);
  59:          }
  60:   
  61:          Console.ReadLine();
  62:      }
  63:  }

And there we have it.

Download Visual Studio 2010 Project (6.69k)

Tags: , , , , , , ,