Thursday, December 4, 2014

default keyword

Introduction:

Ever write some code and wonder if it's possible to default the value to a parameterized type when you don't know if the type is be reference or value, and if it's by value is it numeric or a struct?  Yes you can, .Net back in version 2005 gave us that ability, the default keyword.

Coding:


Time to write some quick code and see how what kind of output default gives us.  I'm still a fan of the works of Tolkein, lets see how we can incorporate both concepts into a simple program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DefaultKeyword
{
  class Program
  {
    class Hobbit
    {
      public string Bilbo { get; set; }
    }

    struct Citizen
    {
      public int Gimli { get; set; }
      public Hobbit Frodo { get; set; }
    }

    static void Main(string[] args)
    {
      int n = default(int);
      Hobbit f = default(Hobbit);
      Citizen b = default(Citizen);

      Console.WriteLine("default value of int n is " + n);
      if (f == null) Console.WriteLine("f is null");

      Console.WriteLine("b.Gimli = {0}", b.Gimli);
      if (b.Frodo == null) Console.WriteLine("b.Frodo is null");

      Console.WriteLine("\nPress Any Key to Exit.");
      Console.ReadKey();

    }
  }
}

Output:
















Huzzah!  The int type defaults to 0, the rest defaulted to null.

Source:

No comments:

Post a Comment