Subscribe

RSS Feed (xml)

Creating Default Object of Type Parameter

When writing generic code, there will be times when the difference between value types and parameter types is an issue. One such situation occurs when you want to give an object of a type parameter a default value. For reference types, the default value is null. For non-struct value types, the default value is 0. The default value for a struct is an object of that struct with all fields set to their defaults. Thus, trouble occurs if you want to give a variable of a type parameter a default value. What value would you use-null, 0, or something else?

For example, given a generic class called Test declared like this:

class Test<T> {
  T obj;
  // ...

if you want to give obj a default value, would you use

obj = null; // works only for reference types

or

obj = 0; // works only for numeric types and enums, but not structs

Neither approach works in all cases.

The solution to this problem is to use another form of the default keyword, shown here:

default(type)

This produces a default value of the specified type, no matter what type is used. Thus, continuing with the example, to assign obj a default value of type T, you would use this statement:

obj = default(T);

This will work for all type arguments, whether they are value or reference types.

Here is a short program that demonstrates default:

// Demonstrate the default keyword.

using System;

class MyClass {
  //...
}

// Construct a default object of T.
class Test<T> {
  public T obj;

  public Test() {
    // The following statement would work
    // only for reference types.
//    obj = null;

    // This statement works for both
    // reference and value types.
    obj = default(T);
  }

  // ...
}

class DefaultDemo {
  public static void Main() {
    // Construct Test using a reference type.
    Test<MyClass> x = new Test<MyClass>();

    if(x.obj == null)
      Console.WriteLine("x.obj is null.");

    // Construct Test using a value type.
    Test<int> y = new Test<int>();

    if(y.obj == 0)
      Console.WriteLine("y.obj is 0.");
  }
}

The output is shown here:

x.obj is null.
y.obj is 0.

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail