Categories

“default” keyword

Just found out today late morning about the usage of keyword “default”.
Bet it, the most popular situation to use it is when doing some logic in switch-case statement like this.

switch(num)
{
	case 1:
		System.Console.WriteLine("num is 1");
		break;
	case 2:
		System.Console.WriteLine("num is 2");
		break;
	default:
		System.Console.WriteLine("num could be others");
		break;
}

It means if “num” is not 1, and 2 then the code will flow into the default section as its name explains.

But for what I gonna say for another case is that, we could use “default” to return the default value setting for 2 different type of variables which are “value type”, and “reference type” in which in that time we don’t know exactly what type of that variable is, the generic type. That is for default, for “value type” it will return zero value set for all attributes (in case of structure), and for “reference type” it will return null.
Consider the example code below.

public class PreservedDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
...
	public TValue GetLastValue()
	{
		if (base.Count > 0)
		        return base[preservedKeys[base.Count-1]];
		else
			return default(TValue);
	} 
...
}

This method resides in a generic class extended from Dictionary class. In that time, we could not know what type of the return variable would be, so by putting “default” keyword we could return the default value from the method.

I usually don’t learn coding by the grammatically way. I tend to build the new found from what I already know and use it. Maybe I should now this long time ago, arhh grin !!!

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">