Nick Grattan's Blog

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

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

3 Responses

Subscribe to comments with RSS.

  1. That probably means that they used code generation to create the sample. It is much simpler to write:

    than it is to write some reflection code and code up the default instantiation values table ( inside a switch statement and a couple of ifs to handle edge cases.


    August 22, 2007 at 9:25 pm

  2. very interesting, but I don’t agree with you


    December 15, 2007 at 1:31 pm

  3. You are right. Assigning amount = 0 is easy and simpler!


    January 18, 2010 at 2:38 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: