Period Class

CSharp · Console

/Program.cs

using System;
					
public class Program
{
	public static void Main()
	{
		var date1=new Period("Jan",2014);
		var date2=new Period();
		Console.WriteLine("First Date is {0}",date1);
		Console.WriteLine("Second Date is {0}",date2);
		if(date1==date2)
			Console.WriteLine("First Date is the same as second date value");
		else if(date1<date2)
			Console.WriteLine("First Date is less than the second date value");
		else 
			Console.WriteLine("First Date is greater than the second date value");
	}
}

public class Period:IComparable
{
	public Period()
	{
		this.Month="Present";
	}
	
	public Period(string Month,int Year)
	{
		this.Month=Month;
		this.Year=Year;
	}
	
	public int CompareTo(object obj)
	{
		if(obj==null)
			return 1;
		Period period = obj as Period;
        if (period != null) 
		{
			if(this.Month=="Present" && period.Month=="Present")
				return 0;
			else if(period.Month=="Present")
				return -1;
			else if(this.Month=="Present")
				return 1;
			else
			{
				DateTime date;
				DateTime periodDate;
				if(!DateTime.TryParse(string.Format("01 {0} {1}",Month,Year),out date))
					throw new ArgumentException("Instance is not a valid Period!");				
				if(!DateTime.TryParse(string.Format("01 {0} {1}",period.Month,period.Year),out periodDate))
					throw new ArgumentException("Object is not a valid Period!");
				return date.Date.CompareTo(periodDate.Date);
			}
		}
        else 
           throw new ArgumentException("Object is not a Period");
	}
	
	public override int GetHashCode()
	{
		if(this==null)
			return 0;
		else
		{
			DateTime date;
			if(!DateTime.TryParse(string.Format("01 {0} {1}",Month,Year),out date))
				throw new ArgumentException("Instance is not a valid Period!");			
			return date.GetHashCode();
		}
	}
	
	public override bool Equals(object obj)
	{
		return this.CompareTo(obj)==0;
	}
	
	public static bool operator==(Period left, Period right)
    {
        return left.Equals(right);
    }
	
	public static bool operator!=(Period left, Period right)
    {
        return !(left==right);
    }
	
	public static bool operator<(Period left, Period right)
    {
        return left.CompareTo(right)<0;
    }
	
	public static bool operator>(Period left, Period right)
    {
        return left.CompareTo(right)>0;
    }
	
	public override string ToString()
	{
		if(string.IsNullOrWhiteSpace(Month))
			return string.Empty;
		else if(Month=="Present")
			return Month;
		else 
			return string.Format("{0} {1}",Month,Year);
	}
	
	public string Month{get; set;}
	public int Year{get; set;}
}
;