4.7. The Default Keyword

When you're dealing with the implementation of a generic class, you may come across situations where you'd like to assign or access default values for your type parameters. However, because the actual type of your type parameter is unknown at the point of implementation, you have no way of knowing what's a valid default value for any given type parameter. To address this need, the generics specification introduced a new "default" keyword. This keyword was needed to allow you to determine the default value for generic types.

The language specification identifies a set of rules for the default values that will be returned for specific types of type parameters. These rules are as follows:

  1. If a type parameter is s reference type, it will always return a default value of null.

  2. If a type parameter is one of the built-in types, the default value will be assigned to whatever default is already defined for that type.

  3. If a type parameter is a struct type, the default value will be the predefined default value for each of the fields defined in that struct.

This mechanism is essential in the implementation of some class types. Here's a simple example that demonstrates one application of the default keyword:

[C# code]
using System.Collections.Generic;

public class MyCache<K, V> {
private Dictionary<K, V> _cache; public V LookupItem(K key) { V retVal; if (_cache.ContainsKey(key) == true) _cache.TryGetValue(key, out retVal); else retVal = default(V); return retVal; } } ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.