Saturday, December 03, 2005 12:16 AM bart

C# 2.0's default keyword

Just a bit more of C# 2.0 language evangelism. Everyone who's familiar with C-style programming languages knows the use of the "default" keyword in the context of a switch statement. However, C# 2.0 introduces the "default" keyword in another context as well, as shown below:

class Def
{
   public static void Main()
   {
      System.Console.WriteLine(Bool());
      System.Console.WriteLine(Int());
      System.Console.WriteLine(IntA());
   }

   public static bool Bool()
   {
      return default(bool);
   }

   public static int Int()
   {
      return default(int);
   }

   public static int? IntA()
   {
      return default(int?);
   }
}

In fact, this is nothing more than a wrapper around the default values of various types, but it can be convenient in some scenarios. Think of automatic code generation for a while, isn't that trivial using this? Or even better, in the context of generic classes, what this feature was originally intended for (e.g. default(T) where T is a type param of a generic class). I hope everyone is familiar with the int? syntax of C# 2.0 as well. This language feature is called nullable types and allows "value types" to have a null value by wrapping those in an instance of (the generic class) System.Nullable.

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# links for 2008-09-23 « Praveen’s Blog

Tuesday, September 23, 2008 10:20 AM by links for 2008-09-23 « Praveen’s Blog

Pingback from  links for 2008-09-23 « Praveen’s Blog