Posted by: Cirilo Meggiolaro | 11/14/2008

Tip of the day #31 – Default keyword

.NET developers have seen the default keyword in use with switch statements, but the default keyword has a different usage when we talk about generics.

Some generic classes don’t know exactly if a value type or a reference type will be passed as a parameter, so the default keyword may be used to enforce that either the value zero or a null value be retrieved for objects without any initialization data.

Example

public class My<T>
{
public T MyGet()
{
return default(T);
}
}

My<int> t = new My<int>();

/// Retrieve 0
Console.WriteLine(t.Get());

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Categories

%d bloggers like this: