Nick Grattan's Blog

About Microsoft SharePoint, .NET, Natural Language Processing and Machine Learning

Archive for the ‘Uncategorized’ Category

Wierd use of C# ‘default’ keyword

with 3 comments

While looking through some Microsoft sample code I came across this:

public int amount = default(System.Int32);

The ‘default’ key word is normally used to initialise a member in a template class when you do not know what the type of the template class will be. For example, here’s an example from MSDN help:

public class GenericList
{
  private class Node
  {
  //
  public Node Next;
  public T Data;
  }

  private Node head;
  public T GetNext()
  {
      T temp = default(T);
...
  }
}

The type ‘T’ is parameterised type for the template. With the line in bold the type ‘T’ could be a numeric value (so the variable should be initialised to ‘0’) or a reference (and so should be initialised to NULL). Using ‘default’ here makes sure the correct initialisation takes place.

Going back to the example from Microsoft, surely this should be just written as:

 public int amount = 0;

since there are no generics involved in this at all?

Written by Nick Grattan

June 27, 2007 at 8:24 pm

Posted in Uncategorized