Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 772115
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T18:45:36+00:00 2026-05-14T18:45:36+00:00

Is there a way to override extension methods (provide a better implementation), without explicitly

  • 0

Is there a way to override extension methods (provide a better implementation), without explicitly having to cast to them? I’m implementing a data type that is able to handle certain operations more efficiently than the default extension methods, but I’d like to keep the generality of IEnumerable. That way any IEnumerable can be passed, but when my class is passed in, it should be more efficient.

As a toy example, consider the following:

// Compile: dmcs -out:test.exe test.cs

using System;

namespace Test {
    public interface IBoat {
        void Float ();
    }

    public class NiceBoat : IBoat {
        public void Float () {
            Console.WriteLine ("NiceBoat floating!");
        }
    }

    public class NicerBoat : IBoat {
        public void Float () {
            Console.WriteLine ("NicerBoat floating!");
        }

        public void BlowHorn () {
            Console.WriteLine ("NicerBoat: TOOOOOT!");
        }
    }

    public static class BoatExtensions {
        public static void BlowHorn (this IBoat boat) {
            Console.WriteLine ("Patched on horn for {0}: TWEET", boat.GetType().Name);
        }
    }

    public class TestApp {
        static void Main (string [] args) {
            IBoat niceboat = new NiceBoat ();
            IBoat nicerboat = new NicerBoat ();

            Console.WriteLine ("## Both should float:");
            niceboat.Float ();
            nicerboat.Float ();
            // Output:
            //      NiceBoat floating!
            //      NicerBoat floating!

            Console.WriteLine ();
            Console.WriteLine ("## One has an awesome horn:");
            niceboat.BlowHorn ();
            nicerboat.BlowHorn ();
            // Output:
            //      Patched on horn for NiceBoat: TWEET
            //      Patched on horn for NicerBoat: TWEET

            Console.WriteLine ();
            Console.WriteLine ("## That didn't work, but it does when we cast:");
            (niceboat as NiceBoat).BlowHorn ();
            (nicerboat as NicerBoat).BlowHorn ();
            // Output:
            //      Patched on horn for NiceBoat: TWEET
            //      NicerBoat: TOOOOOT!

            Console.WriteLine ();
            Console.WriteLine ("## Problem is: I don't always know the type of the objects.");
            Console.WriteLine ("## How can I make it use the class objects when the are");
            Console.WriteLine ("## implemented and extension methods when they are not,");
            Console.WriteLine ("## without having to explicitely cast?");
        }
    }
}

Is there a way to get the behavior from the second case, without explict casting? Can this problem be avoided?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T18:45:37+00:00Added an answer on May 14, 2026 at 6:45 pm

    Extension methods are static methods, and you can’t override a static method. Nor can you “override” an actual instance method with a static/extension method.

    You’ll have to use your optimized extension explicitly. Or implicitly by referencing your own extension’s namespace instead of System.Linq.

    Or explicitly check the type in your extension and call the correct one based on the runtime type.

    This seems like a problem better suited for inheritance than extension methods. If you want different functionality based on the runtime type, then make the base method virtual and override it in the derived classes.

    I see a lot of confusion over this aspect of extension methods. You have to understand that they aren’t mixins, they don’t actually get injected into the class. They’re just syntactic sugar that the compiler recognizes and “allows” you to execute it as if it were a regular instance method. Imagine that it wasn’t an extension method, just a static method instead:

    public static void BlowHorn (IBoat boat) {
        Console.WriteLine ("Patched on horn for {0}: TWEET", boat.GetType().Name);
    }
    

    How would you “override” this method from the IBoat implementation? You can’t. The only thing you can do is put type checking into this static method, or write some dynamic method invocation code, either using a dynamic block in C# 4 or Reflection in earlier versions.

    To make this even clearer, have a look at this code from the System.Linq.Enumerable class out of Reflector:

    public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, 
        int index)
    {
        TSource current;
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
            IList<TSource> list = source as IList<TSource>;
        if (list != null)
        {
            return list[index];
        }
    // ...
    }
    

    This is one of the core extension methods in the .NET Framework. It allows optimization by explicitly checking if the parameter implements IList<T>. Other than this, it has no way of knowing whether or not the underlying concrete type actually supports indexed access. You’d have to do it this same way; create another interface like IHorn or something, and in your extension, check whether or not the IBoat also implements IHorn, same as the Enumerable class does here.

    If you don’t control the code for either the IBoat classes or the extension methods, then you’re out of luck. If you do, then use multiple-interface inheritance, explicit type checking, or dynamic code, those are your options.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 393k
  • Answers 393k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer http://frank-mich.com/jQuery/ May 15, 2026 at 2:05 am
  • Editorial Team
    Editorial Team added an answer s.send is not guaranteed to send every byte you give… May 15, 2026 at 2:05 am
  • Editorial Team
    Editorial Team added an answer I haven't done any Android development, so I'm not sure… May 15, 2026 at 2:05 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.