«^»
8.1. A class declaration for dates

Chapter 11 of the 'C# Language Specification' ([6]) says that ‘Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs.’ So, if we want to represent dates in a program, it would probably be desirable to provide a struct type. However, we will be Java-luddites and use a class type.

So here is a class declaration for dates:

namespace utility
{
    using IComparable = System.IComparable;
    public class Date: IComparable
    {
        private int iYear;
        private int iMonth;
        private int iDay;
        public Date(int pYear, int pMonth, int pDay)
        {
            iYear  = pYear;  iMonth = pMonth;  iDay = pDay;
        }
        public int Year
        {
            get { return iYear;   } 
            set { iYear = value;  }
        }
        public int Month
        {
            get { return iMonth;  }
            set { iMonth = value; }
        }
        public int Day
        {
            get { return iDay;    }
            set { iDay = value;   }
        }
        ...
        public override string ToString()
        {
            return iYear + "-" + iMonth/10 + iMonth%10 
                         + "-" +   iDay/10 +   iDay%10;
        }
    }
}

The first line of the class declaration is:

public class Date: IComparable

If a colon is present, a comma-separated list of names should be given following the colon. If you wish to derive a class from a particular base class, the first name should be the name of this base class; otherwise the class will be derived from the class object. The remaining names should be the names of interfaces that are implemented by this class. So the above line says that the Date class is derived from the class object and that it implements the IComparable interface.

The Date class declaration provides three private fields, a constructor, three properties and a ToString method. These can be used as follows:

Date tDate = new Date(2001, 3, 13);
int  tYear = tDate.Year;
tDate.Year = 2002;
Console.WriteLine(tDate);

The first occurrence of tDate.Year will use the get accessor for Year and the assignment to tDate.Year uses its set accessor.

There are three kinds of properties:

Curiously, get, set and value are not keywords: they are tokens that have a special meaning in the context of a property.

The default access for a member of a class is private and so the three occurrences of the private keyword in the above class declaration can be removed.

The override keyword has to be provided in the declaration of ToString because ToString is a virtual method of the class object (which is Date's base class). There is more information about this topic later.