Community discussion forum

Error when using Method Extensions

  • 1 year ago
    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:
    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

  • 1 year ago

    I found the solution.

    The issue is that the Object class contains a static method with 2 parameters of type Object. Since the .NET Framework first looks at the methods declared within the class, this one is used which is not possible to use on an instance.

     Greetz,

     Geert

Post a reply

Enter your message below

Sign in or Join us (it's free).

Want to stay in touch with what's going on? Follow us on twitter!