Skip to content

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


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.


Respond to this