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. Extension Methods in C# [modified]

Extension Methods in C# [modified]

Scheduled Pinned Locked Moved The Lounge
csharpcomlinqdesign
44 Posts 15 Posters 0 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.
  • S Scott Dorman

    Marc, Take a look at these two blog posts...they may help explain extension methods a bit better: C# 3.0 Extension Methods Follow Up[^] Generic Enum Parsing with Extension Methods[^] Rhino Mocks + Extension Methods + MVC == Crazy Delicious[^] The reality of extension methods is that when you write them, you really are just writing a static class of helper methods. The only difference is the use of the this keyword in front of the first parameter. You can access them using the extension syntax or through the helper class. In fact, if you look at the code in reflector, you will see that the compiler is actually accessinng the method through the static class just like you would normally do. The extension syntax is simply more syntatic sugar. The benefit of using extension methods starts to show by providing a more natural syntax for the helper methods. Your example of Tools.StringToUpper(s) is actually good in that the natural way to think about this is I want to make the current string object's value upper case. Given this, it's more natural to see code like this (although in this case, the name makes it a bit awkward):

    string s = "this is a test";
    s.StringToUpper();

    rather than code like this

    string s = "this is a test";
    s = Tools.StringToUpper(s);

    I'm not sure I agree with the statement that one is more readable than the other; I think they are both equally readable. However, I think the extension method "flows" better and shows the intent with slightly less code at the calling site.

    Scott.


    —In just two days, tomorrow will be yesterday. [

    C Offline
    C Offline
    chaiguy1337
    wrote on last edited by
    #26

    I am concerned about one thing: the fact that the use of the extension method does not mention "where" the method comes from. What if you define two (independent) extension methods called StringToUpper()? How does the compiler know which one to choose, and more importantly, can it be disambiguated by saying something like: s.(Tools.StringToUpper)(); ...? Obviously it wouldn't look like that, but the question stands. Logan

    {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

    D S 2 Replies Last reply
    0
    • C chaiguy1337

      I am concerned about one thing: the fact that the use of the extension method does not mention "where" the method comes from. What if you define two (independent) extension methods called StringToUpper()? How does the compiler know which one to choose, and more importantly, can it be disambiguated by saying something like: s.(Tools.StringToUpper)(); ...? Obviously it wouldn't look like that, but the question stands. Logan

      {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

      D Offline
      D Offline
      Dan Neely
      wrote on last edited by
      #27

      I'd assume it'd work the same way as disambiguation between other namespace collisions.

      -- Help Stamp Out and Abolish Redundancy The preceding is courtesy of the Department of Unnecessarily Redundant Repetition Department.

      E 1 Reply Last reply
      0
      • D Dan Neely

        I'd assume it'd work the same way as disambiguation between other namespace collisions.

        -- Help Stamp Out and Abolish Redundancy The preceding is courtesy of the Department of Unnecessarily Redundant Repetition Department.

        E Offline
        E Offline
        emiaj
        wrote on last edited by
        #28

        it doesn't compile, the compiler throw an exception saying that there is an ambiguous call or something like that, just checked in vs2008

        E 1 Reply Last reply
        0
        • E emiaj

          it doesn't compile, the compiler throw an exception saying that there is an ambiguous call or something like that, just checked in vs2008

          E Offline
          E Offline
          emiaj
          wrote on last edited by
          #29

          the exception message says : "The call is ambiguous between the following methods or properties: '...()' and '...()' ... "

          C 1 Reply Last reply
          0
          • G GoomaJooma

            string s = "this is a test"; s.StringToUpper(); Nothing against extension methods, but I don't actually agree that this example is a good one. If extension methods are just a cosy way of making static helpers look like instance methods on the class in question, one thing they should surely never do is change the semantics of working with that class? Your code sample makes it look like string is not immutable. I suppose the readability is arguable, but it is certainly confusing to people unfamiliar with the class being extended and could lead to bugs being introduced elsewhere, especially on classes less well known or in third party libraries. The following, for example, wouldn’t behave as expected. string s = "this is a test"; s.StringToUpper(); s.Trim();

            S Offline
            S Offline
            Scott Dorman
            wrote on last edited by
            #30

            I used this example since it was the code that Marc was specifically mentioning. Looking at it, the example probably should have been

            string s = "this is a test";
            s = s.StringToUpper();

            which would have clearly shown that it isn't changing the semantics of working with the class and making a string mutable. That should also resolve your other concern about it being used improperly since it would provide the same behavior.

            Scott.


            —In just two days, tomorrow will be yesterday. [Forum Guidelines] [Articles] [Blog]

            1 Reply Last reply
            0
            • C chaiguy1337

              I am concerned about one thing: the fact that the use of the extension method does not mention "where" the method comes from. What if you define two (independent) extension methods called StringToUpper()? How does the compiler know which one to choose, and more importantly, can it be disambiguated by saying something like: s.(Tools.StringToUpper)(); ...? Obviously it wouldn't look like that, but the question stands. Logan

              {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

              S Offline
              S Offline
              Scott Dorman
              wrote on last edited by
              #31

              It was pointed out here[^] that this would actually cause a compiler error. Effectively, the compiler wouldn't know which one to choose and so throws an error telling you that it is an ambiguous call. I don't think it's actually possible to disambiguate the call like that. There are two options:

              1. Choose only one namespace to include.
              2. Use the more traditional static helper class method calling syntax and not the extension method syntax.

              I think the language rules that would be required to do this would be way too complex and the frequency such a situation might arise would be too low to warrant trying to figure out how to do this.

              Scott.


              —In just two days, tomorrow will be yesterday. [Forum Guidelines] [Articles] [Blog]

              C 1 Reply Last reply
              0
              • E emiaj

                the exception message says : "The call is ambiguous between the following methods or properties: '...()' and '...()' ... "

                C Offline
                C Offline
                chaiguy1337
                wrote on last edited by
                #32

                Interesting. Seems to me this is something of an oversight.

                {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

                1 Reply Last reply
                0
                • T tec goblin

                  >>Warned by who? I think the biggest problem will be the potential for abuse by new/inexperienced programmers...but that is the case for almost any language construct. I have seen it in the explanation of the new features in MSDN articles, that extension methods should be used with caution. As for new/inexperienced programmers, my experience is that they tend to be familiarised only with the basic things that are common in java and c#, and most won't even think of using extension methods. Then they might discover them, they might use them once or twice erroneously, but that's ok and natural.

                  S Offline
                  S Offline
                  Scott Dorman
                  wrote on last edited by
                  #33

                  I think the more important thing to understand about extension methods are that they aren't the proverbial "big hammer". They should be used only when other approaches aren't suitable or possible. That being said, I do think there are a lot of opportunities where extension methods make perfect sense (generally for data validation type classes, or most of the other static helper classes you might have).

                  Scott.


                  —In just two days, tomorrow will be yesterday. [Forum Guidelines] [Articles] [Blog]

                  1 Reply Last reply
                  0
                  • S Scott Dorman

                    It was pointed out here[^] that this would actually cause a compiler error. Effectively, the compiler wouldn't know which one to choose and so throws an error telling you that it is an ambiguous call. I don't think it's actually possible to disambiguate the call like that. There are two options:

                    1. Choose only one namespace to include.
                    2. Use the more traditional static helper class method calling syntax and not the extension method syntax.

                    I think the language rules that would be required to do this would be way too complex and the frequency such a situation might arise would be too low to warrant trying to figure out how to do this.

                    Scott.


                    —In just two days, tomorrow will be yesterday. [Forum Guidelines] [Articles] [Blog]

                    C Offline
                    C Offline
                    chaiguy1337
                    wrote on last edited by
                    #34

                    Since when did computer scientists ignore cases that were too "infrequent" to bother worrying about?? It seems to me the fact that this MIGHT happen even once during the course of a project is enough to warrant providing an elegant solution. I suppose the solution is, as you say, to simply resort to calling the method in the conventional static way (I presume this is still possible with extension methods), but it just doesn't feel like a "complete" solution to me. *shrug* I still think extension methods sound really handy, so I'll quite griping now. ;)

                    {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

                    S 1 Reply Last reply
                    0
                    • C chaiguy1337

                      Since when did computer scientists ignore cases that were too "infrequent" to bother worrying about?? It seems to me the fact that this MIGHT happen even once during the course of a project is enough to warrant providing an elegant solution. I suppose the solution is, as you say, to simply resort to calling the method in the conventional static way (I presume this is still possible with extension methods), but it just doesn't feel like a "complete" solution to me. *shrug* I still think extension methods sound really handy, so I'll quite griping now. ;)

                      {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

                      S Offline
                      S Offline
                      Scott Dorman
                      wrote on last edited by
                      #35

                      logan1337 wrote:

                      suppose the solution is, as you say, to simply resort to calling the method in the conventional static way (I presume this is still possible with extension methods), but it just doesn't feel like a "complete" solution to me.

                      Yes, calling the method in the conventional static way is still possible. In fact, that's actually what the compiler converts the code to anyway.

                      logan1337 wrote:

                      Since when did computer scientists ignore cases that were too "infrequent" to bother worrying about?? It seems to me the fact that this MIGHT happen even once during the course of a project is enough to warrant providing an elegant solution.

                      If this were a completely pure science I would agree with you on this point, but at some point a trade off must be made between implementing the pure (elegant) solution that accounts for 100% of all cases, including the edge cases, and the one that implements 99% as long as there is a viable workaround for the remaining edge cases.

                      Scott.


                      —In just two days, tomorrow will be yesterday. [Forum Guidelines] [Articles] [Blog]

                      C 1 Reply Last reply
                      0
                      • S Scott Dorman

                        logan1337 wrote:

                        suppose the solution is, as you say, to simply resort to calling the method in the conventional static way (I presume this is still possible with extension methods), but it just doesn't feel like a "complete" solution to me.

                        Yes, calling the method in the conventional static way is still possible. In fact, that's actually what the compiler converts the code to anyway.

                        logan1337 wrote:

                        Since when did computer scientists ignore cases that were too "infrequent" to bother worrying about?? It seems to me the fact that this MIGHT happen even once during the course of a project is enough to warrant providing an elegant solution.

                        If this were a completely pure science I would agree with you on this point, but at some point a trade off must be made between implementing the pure (elegant) solution that accounts for 100% of all cases, including the edge cases, and the one that implements 99% as long as there is a viable workaround for the remaining edge cases.

                        Scott.


                        —In just two days, tomorrow will be yesterday. [Forum Guidelines] [Articles] [Blog]

                        C Offline
                        C Offline
                        chaiguy1337
                        wrote on last edited by
                        #36

                        Scott Dorman wrote:

                        If this were a completely pure science I would agree with you on this point, but at some point a trade off must be made between implementing the pure (elegant) solution that accounts for 100% of all cases, including the edge cases, and the one that implements 99% as long as there is a viable workaround for the remaining edge cases.

                        In the sense that if the choice is between having the functionality right now with a few edge cases and having to wait for Microsoft's next language, then I completely agree with you. ;)

                        {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

                        1 Reply Last reply
                        0
                        • C chaiguy1337

                          Super Lloyd wrote:

                          Only the compiler can use them (not the runtime)

                          Does this mean there is no reflective ability to obtain a set of extension methods for a given class at runtime... even to do so manually? That is, is there a standard convention by which the static IL methods are named/attributed that would allow them to be identified at runtime and invoked programmatically?

                          {o,o}.oO( Did somebody say “mouse”? ) |)””’) -”-”-

                          S Offline
                          S Offline
                          Super Lloyd
                          wrote on last edited by
                          #37

                          mmhh.. good question, I don't know... sorry.. :~

                          1 Reply Last reply
                          0
                          • M Marc Clifton

                            Thanks Colin (and everyone else). That helps clarify a few things. I wish the articles on MSDN would say it as clearly and well as you and the other CPians have here. Marc

                            Thyme In The Country
                            Interacx
                            My Blog

                            J Offline
                            J Offline
                            Jesse Jacob
                            wrote on last edited by
                            #38

                            I don't mean to sound like a jerk (which is just a pre-apology for sounding like a jerk ;) ), but they DID say it as clearly as everyone else here did. It looks like you jumped to conclusions looking for the most fishy-sounding quotes, and started attacking a strawman. For example: "This is not a standard object-oriented concept; it is a specific Microsoft® .NET Framework implementation feature. While this feature opens up a new set of possibilities, it's worth noting that the underlying intermediate language (IL) code generated by the compiler is really doing nothing new or specific to the .NET Framework 3.5. In actuality, it is simply making a shared method call. This means you have the capability to use this feature in Visual Basic 2008 to target earlier versions of the .NET Framework. It shouldn't introduce any additional security issues since this feature doesn't change the type being extended and doesn't actually do anything that you couldn't already do with earlier versions of the Framework." That stuff in bold is the text immediately following your "red flag". Pretty much answers all of your concerns. I don't even get the red flag comment though: if you don't trust the implementation of the .NET framework, what are you doing programming with it? Are you also mistrustful of CAS, delegates, enums, and foreach? There is no overriding global standard for implementing garbage-collected, language-neutral, object-oriented frameworks...so it's pretty much ALL ABOUT the "implementation features". Get used to it.

                            M 1 Reply Last reply
                            0
                            • S Super Lloyd

                              Extension method are normal method. Only the compiler can use them (not the runtime), as per the documentation: "In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending." elsewhere in the documentation: "You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself." As you can see, they are only syntaxic sugar. I like them, of course I still need to define in my static helper class, but I like to see the new utility method appear on the class I use! :-D (plus intellisense has a special symbol for them, in the combobox, so you know they are extension) Plus I confidently know I didn't break anything, they are just syntaxic sugar.

                              J Offline
                              J Offline
                              Jesse Jacob
                              wrote on last edited by
                              #39

                              Extensions are just syntactic sugar covering the actual static method implementation in the IL. Reflection will have no trouble sorting them from the native type's members.

                              1 Reply Last reply
                              0
                              • M Marc Clifton

                                Judah Himango wrote:

                                compiles down to essentially something like this:

                                So, the implication is that Linq is syntactical frosting on top of extension methods, which is syntactical sugar? [edit] Furthermore, the implication is that Linq could be done without extension methods, in contradiction to what the author in the first article I link to states [/edit] Marc

                                Thyme In The Country
                                Interacx
                                My Blog

                                J Offline
                                J Offline
                                Jesse Jacob
                                wrote on last edited by
                                #40

                                There was no implication that LINQ couldn't have been done without extensions, you came away with that on your own. He described the problem (needing to extend IEnumerable(Of T) in order to support LINQ, but not wanting the trouble of breaking or replacing it), a solution (extensions), and then three full paragraphs explaining how extensions just provide easier syntax without affecting the compiled output. That's the usual definition of syntactic sugar, my friend.

                                1 Reply Last reply
                                0
                                • J Jesse Jacob

                                  I don't mean to sound like a jerk (which is just a pre-apology for sounding like a jerk ;) ), but they DID say it as clearly as everyone else here did. It looks like you jumped to conclusions looking for the most fishy-sounding quotes, and started attacking a strawman. For example: "This is not a standard object-oriented concept; it is a specific Microsoft® .NET Framework implementation feature. While this feature opens up a new set of possibilities, it's worth noting that the underlying intermediate language (IL) code generated by the compiler is really doing nothing new or specific to the .NET Framework 3.5. In actuality, it is simply making a shared method call. This means you have the capability to use this feature in Visual Basic 2008 to target earlier versions of the .NET Framework. It shouldn't introduce any additional security issues since this feature doesn't change the type being extended and doesn't actually do anything that you couldn't already do with earlier versions of the Framework." That stuff in bold is the text immediately following your "red flag". Pretty much answers all of your concerns. I don't even get the red flag comment though: if you don't trust the implementation of the .NET framework, what are you doing programming with it? Are you also mistrustful of CAS, delegates, enums, and foreach? There is no overriding global standard for implementing garbage-collected, language-neutral, object-oriented frameworks...so it's pretty much ALL ABOUT the "implementation features". Get used to it.

                                  M Offline
                                  M Offline
                                  Marc Clifton
                                  wrote on last edited by
                                  #41

                                  Jesse Jacob wrote:

                                  but they DID say it as clearly as everyone else here did.

                                  Well, I don't think so. If it had been stated as clearly, I wouldn't have felt confused.

                                  Jesse Jacob wrote:

                                  It looks like you jumped to conclusions looking for the most fishy-sounding quotes, and started attacking a strawman.

                                  Well, yes. That's quite true. But the reason I made the post on CP was to get clarification. OK, I did come off sounding a bit holier-than-thou, so you have a point.

                                  Jesse Jacob wrote:

                                  if you don't trust the implementation of the .NET framework

                                  So far, we've seen language features in C# that aren't really anything new. Even the lambda expression stuff isn't new in the big picture of programming languages. But extension methods is, I feel, unique to .NET. The quote even says that. And frankly, I don't think it's well thought out, for reasons I previously stated. For example, what I'm struggling with is some good use cases for extension methods, so that from use cases, I can extract "best practices". Put yourself in the position of a teacher, who's introducing extension methods to students. So much of what is taught nowadays seems to be "ooh, isn't this a cool technology that you can do x, y, and z with". But that's not what interests me. What I, as a teacher would discuss, is the fundamental problems that the language feature solves, examples (use cases), and best practices so that you know when to apply the language feature and when to consider other options.

                                  Jesse Jacob wrote:

                                  Get used to it.

                                  No. I'm sorry, but I will question things until I understand them and know how to work with them correctly. Marc

                                  Thyme In The Country
                                  Interacx
                                  My Blog

                                  J 1 Reply Last reply
                                  0
                                  • M Marc Clifton

                                    Jesse Jacob wrote:

                                    but they DID say it as clearly as everyone else here did.

                                    Well, I don't think so. If it had been stated as clearly, I wouldn't have felt confused.

                                    Jesse Jacob wrote:

                                    It looks like you jumped to conclusions looking for the most fishy-sounding quotes, and started attacking a strawman.

                                    Well, yes. That's quite true. But the reason I made the post on CP was to get clarification. OK, I did come off sounding a bit holier-than-thou, so you have a point.

                                    Jesse Jacob wrote:

                                    if you don't trust the implementation of the .NET framework

                                    So far, we've seen language features in C# that aren't really anything new. Even the lambda expression stuff isn't new in the big picture of programming languages. But extension methods is, I feel, unique to .NET. The quote even says that. And frankly, I don't think it's well thought out, for reasons I previously stated. For example, what I'm struggling with is some good use cases for extension methods, so that from use cases, I can extract "best practices". Put yourself in the position of a teacher, who's introducing extension methods to students. So much of what is taught nowadays seems to be "ooh, isn't this a cool technology that you can do x, y, and z with". But that's not what interests me. What I, as a teacher would discuss, is the fundamental problems that the language feature solves, examples (use cases), and best practices so that you know when to apply the language feature and when to consider other options.

                                    Jesse Jacob wrote:

                                    Get used to it.

                                    No. I'm sorry, but I will question things until I understand them and know how to work with them correctly. Marc

                                    Thyme In The Country
                                    Interacx
                                    My Blog

                                    J Offline
                                    J Offline
                                    Jesse Jacob
                                    wrote on last edited by
                                    #42

                                    I've had this argument with lots of different .NET and Java programmers: either you're excited about the new stuff or you dread it, seems to me. I'm not in the dread camp. For example, .NET 2.0 gave me a bunch of new controls and framework extensions that made the apps I was already building much faster, and helped me design my newer apps a lot better. .NET 2.0 added WAY more language-changing features to the CLR than 3.5 has. Anonymous methods, nullable types, and generics provide most of the foundation for LINQ, and have had a significant impact on the way I code, at least. If you take the time to learn them (they are optional, except for the newer framework parts that only use generics), they can make hard things easy, and easy things cleaner, resulting in more comprehensible code.

                                    Marc Clifton wrote:

                                    But extension methods is, I feel, unique to .NET. The quote even says that.

                                    They aren't. See Ruby mixins and the decorator pattern. The implication made by the article author is only that extension methods aren't a standard OO concept.

                                    Marc Clifton wrote:

                                    And frankly, I don't think it's well thought out, for reasons I previously stated.

                                    Now we're just beating a dead horse. You're entitled to your opinion on whether or not EM is well thought out, but you haven't presented any evidence. All we have to go on is the weird "there goes Microsoft again!" tone of your initial post, followed by at least 20 posts explaining in detail that you're wrong.

                                    Marc Clifton wrote:

                                    Put yourself in the position of a teacher, who's introducing extension methods to students. So much of what is taught nowadays seems to be "ooh, isn't this a cool technology that you can do x, y, and z with".

                                    Agreed: if you try teaching every bit of syntactic sugar before your students understand control structures, data structures, and classes, you'll probably confuse the heck out of everybody. After they understand the basics, what's the harm? A great example of how the simple addition of partial classes can help n00bs in .NET 2.0 is the winforms designer: the designer now isolates all of its changes in the

                                    .Designer.cs file. In 1.0 and 1.1, a complicated form quickly became enormous and unwieldy, and accidental modifications could blow up the designer.

                                    Marc Clifton wrote:

                                    No. I'm sorry, but I will question

                                    M 1 Reply Last reply
                                    0
                                    • J Jesse Jacob

                                      I've had this argument with lots of different .NET and Java programmers: either you're excited about the new stuff or you dread it, seems to me. I'm not in the dread camp. For example, .NET 2.0 gave me a bunch of new controls and framework extensions that made the apps I was already building much faster, and helped me design my newer apps a lot better. .NET 2.0 added WAY more language-changing features to the CLR than 3.5 has. Anonymous methods, nullable types, and generics provide most of the foundation for LINQ, and have had a significant impact on the way I code, at least. If you take the time to learn them (they are optional, except for the newer framework parts that only use generics), they can make hard things easy, and easy things cleaner, resulting in more comprehensible code.

                                      Marc Clifton wrote:

                                      But extension methods is, I feel, unique to .NET. The quote even says that.

                                      They aren't. See Ruby mixins and the decorator pattern. The implication made by the article author is only that extension methods aren't a standard OO concept.

                                      Marc Clifton wrote:

                                      And frankly, I don't think it's well thought out, for reasons I previously stated.

                                      Now we're just beating a dead horse. You're entitled to your opinion on whether or not EM is well thought out, but you haven't presented any evidence. All we have to go on is the weird "there goes Microsoft again!" tone of your initial post, followed by at least 20 posts explaining in detail that you're wrong.

                                      Marc Clifton wrote:

                                      Put yourself in the position of a teacher, who's introducing extension methods to students. So much of what is taught nowadays seems to be "ooh, isn't this a cool technology that you can do x, y, and z with".

                                      Agreed: if you try teaching every bit of syntactic sugar before your students understand control structures, data structures, and classes, you'll probably confuse the heck out of everybody. After they understand the basics, what's the harm? A great example of how the simple addition of partial classes can help n00bs in .NET 2.0 is the winforms designer: the designer now isolates all of its changes in the

                                      .Designer.cs file. In 1.0 and 1.1, a complicated form quickly became enormous and unwieldy, and accidental modifications could blow up the designer.

                                      Marc Clifton wrote:

                                      No. I'm sorry, but I will question

                                      M Offline
                                      M Offline
                                      Marc Clifton
                                      wrote on last edited by
                                      #43

                                      Jesse Jacob wrote:

                                      but you haven't presented any evidence

                                      Granted. However I think I'm entitled to "intuition" based on 25 years of programming experience. But your point is well taken. When VS2008 is RTM'd, I'll be spending more time with extension methods and I'll investigate it from the perspective of "best practices", and then I will have evidence.

                                      Jesse Jacob wrote:

                                      After they understand the basics, what's the harm?

                                      Oooh. I'm really surprised you ask that. Let's take your partial classes example. The harm is that partial classes now "hides" what should really be a clean separation of concerns--the UI from the business logic. With partial classes, you can forget that you have really not separated these concerns into robust, loosely coupled, easily testable components.

                                      Jesse Jacob wrote:

                                      To reiterate my stance, attacking *optional* syntax changes that have the potential to make cleaner code is just silly, in my opinion.

                                      Well, I still think I was questioning. However, in my experience, optional things are the very things that are abused and misused the most, and demand the some best practices guidance from the get-go.

                                      Jesse Jacob wrote:

                                      I will, however, thank you

                                      hehe. You're welcome.

                                      Jesse Jacob wrote:

                                      and I honestly can't wait to tear into WPF and XLinq on my next project--we've already identified a lot of problems they can help solve.

                                      Since I'm not in that same position, I am definitely interested in what problems they can help solve, if that's something you'd care to continue investing time in discussing with me. :) For my part, what I've benefited tremendously from is the declarative concepts that WPF and WF are founded on. I have clients that instantly "get it" when they realize that the entire UI and UI workflow is defined declaratively on the server, not to mention the databinding as well. As to Linq (x/d/etc), I really need to work with it to see its benefits. It may be that I'm simply working in a different problem domain than others, because I see very little application of Linq for the problems I'm working on. However, I would like to thank you for your discussion so far! Marc

                                      Thyme I

                                      1 Reply Last reply
                                      0
                                      • M Marc Clifton

                                        I was reading this on the MSDN site: A new feature made available in Visual Basic 2008, however, lets you extend any existing type's functionality, even when a type is not inheritable. And these extension methods play a crucial role in the implementation of LINQ. Many types that already exist can't be easily updated without breaking existing code. An example of this is the interface IEnumerable(Of T). In order to support LINQ, new methods had to be added to this interface, but changing the interface by adding new methods would break compatibility with existing consumers. Adding a new interface was a possibility, but creating a new interface to supplement the existing IEnumerable(Of T) interface would have appeared to be an odd design. What was needed was a way to extend existing types with new functionality without changing the existing contract. Is this true? That extension methods were added for the purpose of supporting Linq? The article[^] also makes some wierd points: Extension methods allow you to add functionality to a type that you don't want to modify, thus avoiding the risk of breaking code in existing applications. You can extend standard interfaces with additional methods without physically altering the existing class libraries. You can extend .NET types and older COM/ActiveX® control types for new code without risk of breaking old applications that use these types. Prior to extension methods, in order to add functionality to classes and interfaces, you had a few options: * You could add the functionality to the source code, but this requires access to source code that may not be available. * You could use inheritance to inherit the functionality contained within one type into a new derived type, but not all types were inheritable. * You could re-implement the functionality from scratch. What I find odd about this is the assumption that one would want to add functionality to a class or interface. I mean, what's wrong with just calling, say, a static helper method? The example in the article, the AlternateCase method, seems ridiculous to implement as an extension method. Is this simply because the example is contrived? As the author points out: This is not a standard object-oriented concept; it is a specific Micros

                                        S Offline
                                        S Offline
                                        si618
                                        wrote on last edited by
                                        #44

                                        I think the opportunity for over-use or abuse is present, but I can also see the benefits. As an example, we use the ExtendedProperties of a DataTable and DataColumn quite a bit in our own custom DataSet. Currently we have the code for retrieving these properties values in our DataSet class (as a static helper), but by using extension methods we would be able to place the code against the DataTable and DataColumn classes, which would be a more intuitive place to look. Another example would be the String class, such as adding a ToProperCase() method, much nicer and easier for developer (via intellisense) than a static helper class.

                                        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