GeertVerhoeven
Technical User
Hi all,
I'm practicing with the C# 3.0 Language Enhancements and get stuck with the following issue on method extensions.
The goal is to write an Equals method for the datetime type which accepts an additional parameter indicating until which level the comparison must be done (Year / Month / Day).
The code works when I use the static method directly but when I use the extension method syntax, it doesn't work.
Here is my code:
I hope someone can help me with this.
Greetz,
Geert
Geert Verhoeven
Consultant @ Ausy Belgium
My Personal Blog
I'm practicing with the C# 3.0 Language Enhancements and get stuck with the following issue on method extensions.
The goal is to write an Equals method for the datetime type which accepts an additional parameter indicating until which level the comparison must be done (Year / Month / Day).
The code works when I use the static method directly but when I use the extension method syntax, it doesn't work.
Here is my code:
Code:
using System;
namespace Extension_Methods
{
class Program
{
static void Main(string[] args)
{
DateTime date = new DateTime(2008, 1, 1);
DateTime date2 = new DateTime(2008, 1, 2);
// Code below works
Console.WriteLine(DateTimeUtils.Equals(date, date2, DatePrecision.Month));
// ERROR on line below:
// Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead
Console.WriteLine(date.Equals(date2, DatePrecision.Month));
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
public static class DateTimeUtils
{
public static bool Equals(this DateTime date, DateTime comparisonDate, DatePrecision precision)
{
switch (precision)
{
case DatePrecision.Year:
return date.Year.Equals(comparisonDate.Year);
case DatePrecision.Month:
return date.Year.Equals(comparisonDate.Year) &&
date.Month.Equals(comparisonDate.Month);
case DatePrecision.Day:
return date.Year.Equals(comparisonDate.Year) &&
date.Month.Equals(comparisonDate.Month) &&
date.Day.Equals(comparisonDate.Day);
default:
return false;
}
}
}
public enum DatePrecision
{
Year,
Month,
Day
}
}
I hope someone can help me with this.
Greetz,
Geert
Geert Verhoeven
Consultant @ Ausy Belgium
My Personal Blog