#1,014 – 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.

    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.

            // 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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment