The following examples are from the book Programming in the Key of C#.
The first iteration of the program is the typical C way to do it, and the next reincarnation is more object oriented. The program is a simple example of calculating which day of the year a certain event occurred (december 31 is 365 or 366 if it's a leap year).
using System;
class StructureAndMethodsTwo
{
static void Main()
{
Date dateMoonWalk = new Date();
dateMoonWalk.iYear = 1969;
dateMoonWalk.iMonth = 7;
dateMoonWalk.iDay = 20;
Console.WriteLine("Moon walk: {0}/{1}/{2} Day of Year: {3}",
dateMoonWalk.iMonth, dateMoonWalk.iDay, dateMoonWalk.iYear,
Date.DayOfYear(dateMoonWalk));
}
}
struct Date
{
public int iYear;
public int iMonth;
public int iDay;
public static bool IsLeapYear(int iYear)
{
return iYear % 4 == 0 && (iYear % 100 != 0 || iYear % 400 == 0);
}
static int[] aiCumulativeDays = { 0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334 };
public static int DayOfYear(Date dateParam)
{
return aiCumulativeDays[dateParam.iMonth - 1] + dateParam.iDay +
(dateParam.iMonth > 2 && IsLeapYear(dateParam.iYear) ? 1 : 0);
}
}
The next version of the program is identical except for the DayOfYear method which turns into
public int DayOfYear()
{
return aiCumulativeDays[iMonth -1] + iDay+ (iMonth > 2 && IsLeapYear(iYear) ? 1:0);
}
What's exactly going on in the second version that makes it more OOP friendly than the first? Is an object of type Date being created by the method DayOfYear in the first iteration? I know that the instance version of the method has direct access to the fields of the structure, but I'm not aware of the distinct advantages of it.