Using default Operator in a Generic Class

The default operator provides a valid default value for any type.
One place where this operator is very handy is in a generic class, operating on the type parameter T.  In the example below, we initialize an internal collection of type T so that each element has the proper default value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BagOf<T>
{
    private Collection<T> coll;
    public T SomeItem
    {
        get { return coll[0]; }
    }
 
    public BagOf(int numInBg)
    {
        if (numInBg <= 0)
            throw new Exception("Must have >0 items");
 
        coll = new Collection<T>();
        for (int i = 0; i < numInBg; i++)
            coll.Add(default(T));
    }
}
Using this class, we can see the default values for each type of item.
1
2
3
4
5
6
7
8
9
10
11
// Numeric
BagOf<int> bagOfInt = new BagOf<int>(2);
int anInt = bagOfInt.SomeItem;
 
// Struct
BagOf<Point3D> bagOfPoints = new BagOf<Point3D>(3);
Point3D aPoint = bagOfPoints.SomeItem;
 
// Reference type
BagOf<Dog> bagOfDogs = new BagOf<Dog>(4);
Dog aDog = bagOfDogs.SomeItem;


1014-001