#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++)

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;



About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

%d bloggers like this: