Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. do you use extension methods intensively in your projects?

do you use extension methods intensively in your projects?

Scheduled Pinned Locked Moved The Lounge
question
42 Posts 27 Posters 35 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Sander RosselS Sander Rossel

    OriginalGriff wrote:

    If the class is your own, then it's just silly to use extension methods

    No it's not! On a few occasions I've created an interface, ISomething, and before writing any implementation I wrote a few extension methods I knew I needed. And then I wrote the implementations (and got so much functionality out of the box!) :D Kind of like collections and LINQ, all M$ "own" classes, but they still have lots of extension methods.

    Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

    Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

    Regards, Sander

    B Offline
    B Offline
    BillWoodruff
    wrote on last edited by
    #20

    Hi Sandor, I'd really appreciate seeing an example of Extension Methods for an Interface. cheers, Bill

    «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

    Sander RosselS 1 Reply Last reply
    0
    • B BillWoodruff

      Hi Sandor, I'd really appreciate seeing an example of Extension Methods for an Interface. cheers, Bill

      «There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008

      Sander RosselS Offline
      Sander RosselS Offline
      Sander Rossel
      wrote on last edited by
      #21

      The entire LINQ library depends upon it. For example the Count() extension method on collections may look as follows:

      public static class Extensions
      {
      public static int Count(this IEnumerable collection)
      {
      int count = 0;
      using (var enumerator = collection.GetEnumerator())
      {
      while (enumerator.MoveNext())
      {
      count += 1;
      }
      }
      return count;
      }
      }

      The actual extension method checks for null and tries to cast to ICollection<T> and ICollection for the Count property first, but it's an extension on an interface. There are LOTS of them...

      Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

      Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

      Regards, Sander

      S 1 Reply Last reply
      0
      • M Marc Clifton

        public static bool Yes(this T foo) {return true;}

        Marc

        Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

        S Offline
        S Offline
        Southmountain
        wrote on last edited by
        #22

        very inspirational

        diligent hands rule....

        1 Reply Last reply
        0
        • realJSOPR realJSOP

          My most recent ones calculate business chart trend line values from either an IEnumerable<double> or a IEnumerable<T> using the named property.

          ".45 ACP - because shooting twice is just silly" - JSOP, 2010
          -----
          You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
          -----
          When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

          S Offline
          S Offline
          Southmountain
          wrote on last edited by
          #23

          this is a good one..

          diligent hands rule....

          1 Reply Last reply
          0
          • Sander RosselS Sander Rossel

            The entire LINQ library depends upon it. For example the Count() extension method on collections may look as follows:

            public static class Extensions
            {
            public static int Count(this IEnumerable collection)
            {
            int count = 0;
            using (var enumerator = collection.GetEnumerator())
            {
            while (enumerator.MoveNext())
            {
            count += 1;
            }
            }
            return count;
            }
            }

            The actual extension method checks for null and tries to cast to ICollection<T> and ICollection for the Count property first, but it's an extension on an interface. There are LOTS of them...

            Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

            Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

            Regards, Sander

            S Offline
            S Offline
            Southmountain
            wrote on last edited by
            #24

            thanks for this example!

            diligent hands rule....

            1 Reply Last reply
            0
            • M Marc Clifton

              public static bool Yes(this T foo) {return true;}

              Marc

              Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project! Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny

              M Offline
              M Offline
              Mark_Wallace
              wrote on last edited by
              #25

              Marc Clifton wrote:

              public static bool Yes<T>(this T foo) {return true;}

              That looks suspiciously like an advert for Ty-phoo tea!

              I wanna be a eunuchs developer! Pass me a bread knife!

              1 Reply Last reply
              0
              • S Southmountain

                just curious. recently I start to use extension methods in my projects.

                diligent hands rule....

                F Offline
                F Offline
                Forogar
                wrote on last edited by
                #26

                Extensively, yes. Intensively, no.

                - I would love to change the world, but they won’t give me the source code.

                1 Reply Last reply
                0
                • S Southmountain

                  just curious. recently I start to use extension methods in my projects.

                  diligent hands rule....

                  C Offline
                  C Offline
                  Chris Maunder
                  wrote on last edited by
                  #27

                  We use them in order to have POCO's and then attach extension methods to them to give them some mojo.

                  cheers Chris Maunder

                  F 1 Reply Last reply
                  0
                  • Sander RosselS Sander Rossel

                    OriginalGriff wrote:

                    If the class is your own, then it's just silly to use extension methods

                    No it's not! On a few occasions I've created an interface, ISomething, and before writing any implementation I wrote a few extension methods I knew I needed. And then I wrote the implementations (and got so much functionality out of the box!) :D Kind of like collections and LINQ, all M$ "own" classes, but they still have lots of extension methods.

                    Read my (free) ebook Object-Oriented Programming in C# Succinctly. Visit my blog at Sander's bits - Writing the code you need. Or read my articles here on CodeProject.

                    Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

                    Regards, Sander

                    F Offline
                    F Offline
                    Fabio Franco
                    wrote on last edited by
                    #28

                    Sander Rossel wrote:

                    On a few occasions I've created an interface, ISomething, and before writing any implementation I wrote a few extension methods I knew I needed.

                    Still doesn't make sense to me. If the interface is your own, you should write the method to the interface as it makes sense to be in its scope. If you need behavior without having to implement everywhere, you're looking for an abstract class. Extension methods provide a clean way to have helper methods to class you cannot modify. Otherwise you're just creating spaghetti code and killing a few principles. Although M$ does with it's own classes, it makes sense, specially to not break backwards compatibility when implementing new frameworks (like LINQ), so yes, they own the code, but they should not modify it, as LINQ is implemented in a whole different scope. If you are developing frameworks, with attachable components, that extend other standalone components, yes, it makes sense to have extension methods on your own code, otherwise I agree that's "silly".

                    To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                    Sander RosselS 1 Reply Last reply
                    0
                    • S Southmountain

                      just curious. recently I start to use extension methods in my projects.

                      diligent hands rule....

                      F Offline
                      F Offline
                      Fabio Franco
                      wrote on last edited by
                      #29

                      Extensively sounds funny to me. Unless you are creating a framework of extension methods for built-in or third party types, using it intensively may indicate you're doing something wrong with your code. They have a purpose, be sure you understand it before using it everywhere. It may create unorganized, hard to maintain code.

                      To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                      1 Reply Last reply
                      0
                      • C Chris Maunder

                        We use them in order to have POCO's and then attach extension methods to them to give them some mojo.

                        cheers Chris Maunder

                        F Offline
                        F Offline
                        Fabio Franco
                        wrote on last edited by
                        #30

                        Why not implement in the object themselves and keep them contained and organized? Is there anything preventing the code to be where it belongs?

                        To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                        C 1 Reply Last reply
                        0
                        • F Fabio Franco

                          Sander Rossel wrote:

                          On a few occasions I've created an interface, ISomething, and before writing any implementation I wrote a few extension methods I knew I needed.

                          Still doesn't make sense to me. If the interface is your own, you should write the method to the interface as it makes sense to be in its scope. If you need behavior without having to implement everywhere, you're looking for an abstract class. Extension methods provide a clean way to have helper methods to class you cannot modify. Otherwise you're just creating spaghetti code and killing a few principles. Although M$ does with it's own classes, it makes sense, specially to not break backwards compatibility when implementing new frameworks (like LINQ), so yes, they own the code, but they should not modify it, as LINQ is implemented in a whole different scope. If you are developing frameworks, with attachable components, that extend other standalone components, yes, it makes sense to have extension methods on your own code, otherwise I agree that's "silly".

                          To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                          Sander RosselS Offline
                          Sander RosselS Offline
                          Sander Rossel
                          wrote on last edited by
                          #31

                          I wholeheartedly disagree :D Extension methods are nothing more than static helper methods that are treated as instance methods by the editor (and the compiler?). I don't think there is a principle against creating static helper methods and it's certainly not creating spaghetti, especially since the methods read as instance methods (editor trick or not). An abstract class is heavy weaponry, every implementor must now inherit the abstract class and since you can only inherit once this puts a serious limitation on implementors. If you can't inherit you don't get the functionality. You could create a wrapper, but that's just a lot of boilerplate code. Besides, inheritance is added complexity/spaghetti too!

                          public interface ISomething
                          {
                          IEnumerable Stuff { get; }
                          }

                          public static class SomethingExtensions
                          {
                          public static bool HasStuff(this ISomething something)
                          {
                          return something.Stuff.Any();
                          }
                          }How is this not awesome? Every implementor now gets HasStuff for free without the need for inheritance!

                          You agree that extension methods are clean for LINQ and when dealing with third party code, but for your own code it's suddenly spaghetti? Sounds like double standards to me ;)

                          Read my (free) ebook Object-Oriented Programming in C# Succinctly.
                          Visit my blog at Sander's bits - Writing the code you need.
                          Or read my articles here on CodeProject.

                          Simplicity is prerequisite for reliability.
                          — Edsger W. Dijkstra

                          Regards,
                          Sander

                          1 Reply Last reply
                          0
                          • S Southmountain

                            just curious. recently I start to use extension methods in my projects.

                            diligent hands rule....

                            P Offline
                            P Offline
                            PSU Steve
                            wrote on last edited by
                            #32

                            Yes, quite a bit. I love the extension method concept. Now if they could just implement "extension properties". Yes, I know you can use extension methods to pseudo-implement properties, but a full-blown extension property implementation would be sweet...

                            1 Reply Last reply
                            0
                            • L Lost User

                              I mostly use them for things that can't have methods defined on them directly, interfaces and enums.

                              C Offline
                              C Offline
                              Cameron Oltmann
                              wrote on last edited by
                              #33

                              For some reason I never thought of writing them for enums, though I use them for interfaces all the time. Can you give an example where an extension method for an enum would be useful? Can't think of any myself off hand.

                              L 1 Reply Last reply
                              0
                              • F Fabio Franco

                                Why not implement in the object themselves and keep them contained and organized? Is there anything preventing the code to be where it belongs?

                                To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                                C Offline
                                C Offline
                                Chris Maunder
                                wrote on last edited by
                                #34

                                Separation of concerns, mostly.

                                cheers Chris Maunder

                                1 Reply Last reply
                                0
                                • S Southmountain

                                  just curious. recently I start to use extension methods in my projects.

                                  diligent hands rule....

                                  H Offline
                                  H Offline
                                  Harley L Pebley
                                  wrote on last edited by
                                  #35

                                  The core products for the company I work for are mainly COM based libraries. I've written .Net libraries of extension methods that help hide the COM ugliness and provide a more .Net friendly interface.

                                  1 Reply Last reply
                                  0
                                  • S Southmountain

                                    just curious. recently I start to use extension methods in my projects.

                                    diligent hands rule....

                                    M Offline
                                    M Offline
                                    Matthew Dennis
                                    wrote on last edited by
                                    #36

                                    I have a .NET Core based Redis Client that I've been working on for a while that heavily uses extension methods. The 'client' just knows how to send a command and receive a response. All the Redis commands are implemented as extension methods on the 'client'. So as static class for the Key Commands, another for the Hash Commands, ... in Redis Client

                                    /// <summary>
                                    /// Sends a command and returns the response string.
                                    /// </summary>
                                    /// <param name="command">The Command.</param>
                                    /// <param name="parameters">The parameters.</param>
                                    /// <returns>The response.</returns>
                                    public Task SendAsync(string command, params object[] parameters)
                                    {
                                    return SendAsync(command, (IEnumerable<object>)parameters);
                                    }

                                    /// <summary>
                                    /// Sends a command and returns the response string.
                                    /// </summary>
                                    /// <param name="command">The Command.</param>
                                    /// <param name="parameters">The parameters.</param>
                                    /// <returns>The awaitable Task.</returns>
                                    public async Task SendAsync(string command, IEnumerable<object> parameters = null)
                                    {
                                    await EnsureConnected().ConfigureAwait(false);
                                    await _commandWriter.WriteRedisCommandAsync(command, parameters).ConfigureAwait(false);
                                    }

                                    in HashCommands

                                    public static Task SendHGetAsync(this RedisClient client, string key, string field)
                                    {
                                    if (string.IsNullOrWhiteSpace(key))
                                    throw new ArgumentNullException(nameof(key));

                                    if (string.IsNullOrWhiteSpace(field))
                                        throw new ArgumentNullException(nameof(field));
                                    
                                    return client.SendAsync("HGet", key, field);
                                    

                                    }

                                    Each commands are small and trivial. The core client has no tricky dependencies on the commands. Classic Open for Extension but Closed for Modification. What has been delaying me is the number of tests to test all the commands, plus an update to the latest .NET Core bits. Another great thing about Extension Methods is the ability to extend 3rd party libraries.

                                    "Time flies like an arrow. Fruit flies like a banana."

                                    1 Reply Last reply
                                    0
                                    • C Cameron Oltmann

                                      For some reason I never thought of writing them for enums, though I use them for interfaces all the time. Can you give an example where an extension method for an enum would be useful? Can't think of any myself off hand.

                                      L Offline
                                      L Offline
                                      Lost User
                                      wrote on last edited by
                                      #37

                                      Well it depends on what that enum is about, it's not always useful. I've used it for example to give an `enum ConditionCode { etc` the fake-methods `Invert` and `SwapOperands`.

                                      C 1 Reply Last reply
                                      0
                                      • S Southmountain

                                        just curious. recently I start to use extension methods in my projects.

                                        diligent hands rule....

                                        J Offline
                                        J Offline
                                        Jim Balter
                                        wrote on last edited by
                                        #38

                                        I used them extensively.

                                        1 Reply Last reply
                                        0
                                        • L Lost User

                                          Well it depends on what that enum is about, it's not always useful. I've used it for example to give an `enum ConditionCode { etc` the fake-methods `Invert` and `SwapOperands`.

                                          C Offline
                                          C Offline
                                          Cameron Oltmann
                                          wrote on last edited by
                                          #39

                                          Ah gotcha. Thanks!

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups