This week’s training was on the new features of C# 3.0. Namely:

  • Automatically Implemented Properties
  • Object & Collection Initializers
  • Dynamic Local Variables
  • Anonymous Types
  • Extension Methods

Auto Props, Initializers and Dynamic Local Variables are a godsend to C# devs. It simplifies coding greatly and makes writing unit test cases a breeze.

Old Way

[Test]
public void CalculateInvoiceTotalTest()
{
    Invoice invoice = new Invoice();
    invoice.Items = new List<InvoiceItem>();

    // Add items
    InvoiceItem item = new InvoiceItem();
    item.UnitPrice = 28.50;
    item.Quantity = 2;
    item.Discount = 0.1;
    invoice.Items.Add(i);

    item = new InvoiceItem();
    item.UnitPrice = 5.45;
    item.Quantity = 5;
    invoice.Items.Add(i)

    double expected = 78.55;
    double actual = invoice.Total;

    Assert.IsTrue(actual, expected);
}

New Way

[Test]
public void CalculateInvoiceTotalTest()
{
    Invoice invoice = new Invoice
    {
        Items = new List<InvoiceItem>()
        {
            new InvoiceItem() { UnitPrice = 28.50, Quantity = 2, Discount = 0.1 },
            new InvoiceItem() { UnitPrice = 5.45, Quantity = 5; }
        }
    };

    double expected = 78.55;
    double actual = invoice.Total;
    Assert.IsTrue(actual, expected);
}

It’s a lot clearer that I added 2 invoice items and it only took me one line each to create the line items. Granted you can simplify the old code by using a custom constructor but you still need a line to add the item to the collection.

There were some very good series of Channel 9 run by Bruce Kyle and Stuat Celarier in their Whirlwind series about C#

Comment