08
Sep
2006

Subtleties of .NET: int i; and int i=0 are not the same

Every value type in .NET defaults to a sensible value so you might be thinking that int i and int i = 0 are logically the same.

This is often true however consider the case of a variable declared in-line inside a loop and things are a little different (using Decimal in this example)

foreach(Customer customer in customers) {
    decimal customerSalesYTD = 0;
    foreach(Invoice invoice in customer.Invoices.ForYear(DateTime.Now.Year)
        customerSalesYTD += invoice.Value;
    SalesTotal.Set(customer, customerSalesYTD);
}

Here the 0 makes all the difference because although you have created the variable inside the loop by the time the runtime gets to this the optimizer has moved the object creation to outside the loop.

[)amien

Share with others
  • Digg
  • description
  • StumbleUpon
  • description
  • Reddit
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • Technorati
  • E-mail this story to a friend!

0 Responses to “Subtleties of .NET: int i; and int i=0 are not the same”


  1. No Comments

Leave a reply




Topics