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. C# 4.0

C# 4.0

Scheduled Pinned Locked Moved The Lounge
csharpquestiondiscussionannouncement
233 Posts 75 Posters 282 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 Sunny Ahuwanya

    Pawel Krakowiak wrote:

    I think of them as of an improvement and use them. Smile

    Can anyone explain to me how extension methods are an improvement? Besides helping to sell LINQ and encouraging programmers to write code in a non-portable, non object oriented manner, what is the point of extension methods?

    Sunny Ahuwanya "The beauty of the desert is that it hides a well somewhere" -- Antoine de Saint Exupéry

    J Offline
    J Offline
    Jon Rista
    wrote on last edited by
    #159

    Who says object-orientation is the sole valid way to write code? Object-orientation can get in the way when something simpler would suffice to get the job done. Extension methods allow you to add a great deal of expressiveness to your code, extend base types you don't have direct control of to provide a cleaner API, etc. etc. Whats with all the hostility towards useful language features and non-object-orientedness? Objects don't solve every problem. Portability? Where are you going to "port" a C# or VB.NET app to...they only run on the .NET platform anyway. Use the features for what they are. As a programmer, your job is to provide solutions to business problems in the most effective, efficient, maintainable way possible...don't get so hung up on all the "rules" and "regulations" of OOP...objects arn't the only option.

    J S 2 Replies Last reply
    0
    • P PIEBALDconsult

      Pawel Krakowiak wrote:

      add new functionality to the existing classes

      They do nothing of the sort!

      J Offline
      J Offline
      Jon Rista
      wrote on last edited by
      #160

      They absolutely do! Look at IEnumerable...EVERY type that implements IEnumerable DOES INDEED get the full functionality of all extension methods written for IEnumerable (so long as the proper using statement(s) are included). You don't have to "implement" the extension methods on each class that implements IEnumerable...the extension methods absolutely do add new functionality without you having to do any extra implementation. And that functionality is accessed through class INSTANCES...not static methods or utility types. You anti-progressive types drive me nuts sometimes...get off your high horse and USE the tools at your disposal. You might find that you actually like them.

      P P S 3 Replies Last reply
      0
      • S Sunny Ahuwanya

        On Portability: 1) Imagine if I had to port some C# code from one framework/platform to another. Before C# 3.0, I'd had to make sure I have compatible libraries in the new framework. But now, I also have the added headache of figuring out where ALL the referenced extension methods in the code are and make sure they exist in the new framework (or write equivalent ones). It doesn't help that extension methods share the same dot notation with regular methods. I can't tell what an extension method is just by looking at the call. I'd have to write some tool that will check all referenced assemblies to point out the extension methods in the code. 2) Let's say I'm using LINQ's IEnumerable.Where extension method on a collection class someone else wrote, BUT I didn't realize the other developer had included a .Where regular method that returns an IEnumerable. My code will compile superbly without any warnings. The best part is that this code will work for months until THE CONDITION that differentiates the developer's .Where method and the LINQ's .Where method occurs. On Object Orientedness: Developer A uses List.SingleOrDefault() extensively, developer B creates a new class derived from List but would like .SingleOrDefault() to work a little differently so that all the pre-existing code will work properly with objects derived from his new class. He's stuck. :(

        Sunny Ahuwanya "The beauty of the desert is that it hides a well somewhere" -- Antoine de Saint Exupéry

        J Offline
        J Offline
        Jon Rista
        wrote on last edited by
        #161

        The methods implemented as part of IEnumerable are now intrinsic to the .NET framework. Any decent developer would avoid using identifiers already used in the framework. Your argument about IEnumerable.Where is the same as saying Developer B creates a new class called String... Simple solution, don't do that. Almost any language feature can be missused. Don't missuse them.

        S 1 Reply Last reply
        0
        • S SlingBlade

          How about a way to check against all values in an array or enumerabale at once with perhaps the keyword 'any' like below.

          int[] supportedValues = new int[] { 3, 4, 5 }
          int x = 4;

          if (x == any supportedValues)
          {
          // Do something.
          }

          Instead of:

          int[] supportedValues = new int[] { 3, 4, 5 }
          int x = 4;
          bool xIsSupported = false;

          foreach (int value in supportedValues)
          {
          if (x == value)
          xIsSupported = true;
          }

          if (xIsSupported)
          {
          // Do something.
          }

          Good idea?

          S Offline
          S Offline
          S Senthil Kumar
          wrote on last edited by
          #162

          Why not use the Contains extension method? It's almost similar to your syntax.

                  IEnumerable arr = new int\[\] { 1, 2, 3 };
                  int x = 4;
                  if (arr.Contains(x))
                  {
                      Console.WriteLine("Present");
                  }
          

          Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

          1 Reply Last reply
          0
          • S S Senthil Kumar

            Sunny Ahuwanya wrote:

            non-portable, non object oriented manner

            Hmm, that's interesting. Is it not part of the ECMA spec? Considering there's no runtime support required for extension methods, I can't see any other portability concerns. Or maybe you are considering them non-portable because the calling code won't compile without the presence of the source code containing the extension methods? And yeah, they are non object oriented if you consider static methods in a static class non-object oriented as well.

            Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

            J Offline
            J Offline
            James Lonero
            wrote on last edited by
            #163

            This raises a good point about extension methods. They are not object oriented. If someone wants to write an extension method, then they should write a subclass to the object you want. Then add the desired methods. But, it sounds like LINQ is a (very) popular feature. And, the only way to support LINQ is by extension methods. Then, maybe the question should be is should MS not allow the public (those not writing directly for MS C#) to create extension methods? Keep them internal to the Microsoft C# team for specific requirements of the language (like LINQ).

            1 Reply Last reply
            0
            • R Russell Jones

              I do sort of like the idea but isn't a function by definition a thing that only returns a single value? Maybe we need anonymous returns instead so that you define a struct on the fly, thus returning a single entity that contains the multiple values. public {Max int, Min int} MinMax(int[] numbers) { int min, max; // Code to calculate min/max return {min, max}; } called with var v= MinMax(myArray); system.out.println(v.Min); system.out.println(v.Max); otherwise you'd end up having to create something wierd like this to get the values back int min, max = MinMax(myArray); Russell

              J Offline
              J Offline
              Jon Rista
              wrote on last edited by
              #164

              You could consider the tuple to be a single value. The single value is the tuple as a whole thing. public [int,int] MinMax(int[] numbers) { int min, max; // Compute min and max return tuple[min,max]; } tuple[int,int] result = MinMax(new[] { 1, 2, 3, 5, 8, 13 }); If tuples were added to C# 4.0, I think they should be added properly, with a native syntax for defining them. Perhapse even support for "anonymous" tuples akin to var: public [int,string,string,DateTime] TupleFunc() { return tuple[1, "String 1", "String 2", DateTime.Now]; } tuple result = TupleFunc(); int number = result[0]; string firstString = result[1];

              1 Reply Last reply
              0
              • P PIEBALDconsult

                Pawel Krakowiak wrote:

                add new functionality to the existing classes

                They do nothing of the sort!

                P Offline
                P Offline
                Pawel Krakowiak
                wrote on last edited by
                #165

                PIEBALDconsult wrote:

                They do nothing of the sort!

                string lookingFor = "Wash";
                lookingFor.ToSqlLike(SqlLikePlacement.Front); // returns "Wash%"
                lookingFor.ToSqlLike(SqlLikePlacement.Middle); // returns "%Wash%"
                lookingFor.ToSqlLike(SqlLikePlacement.End); // returns "%Wash"

                I understand I missed something and the above code is possible without extension methods and without creation of a new class?

                P 1 Reply Last reply
                0
                • S SlingBlade

                  How about a way to check against all values in an array or enumerabale at once with perhaps the keyword 'any' like below.

                  int[] supportedValues = new int[] { 3, 4, 5 }
                  int x = 4;

                  if (x == any supportedValues)
                  {
                  // Do something.
                  }

                  Instead of:

                  int[] supportedValues = new int[] { 3, 4, 5 }
                  int x = 4;
                  bool xIsSupported = false;

                  foreach (int value in supportedValues)
                  {
                  if (x == value)
                  xIsSupported = true;
                  }

                  if (xIsSupported)
                  {
                  // Do something.
                  }

                  Good idea?

                  J Offline
                  J Offline
                  Jon Rista
                  wrote on last edited by
                  #166

                  Perhapse this (.NET 3.5 IEnumerable extensions): int[] supportedValues = new int[] {3,4,5}; int x = 4; if (supportedValues.Any(v => v == x)) { // Do something }

                  S 1 Reply Last reply
                  0
                  • J Jon Rista

                    Who says object-orientation is the sole valid way to write code? Object-orientation can get in the way when something simpler would suffice to get the job done. Extension methods allow you to add a great deal of expressiveness to your code, extend base types you don't have direct control of to provide a cleaner API, etc. etc. Whats with all the hostility towards useful language features and non-object-orientedness? Objects don't solve every problem. Portability? Where are you going to "port" a C# or VB.NET app to...they only run on the .NET platform anyway. Use the features for what they are. As a programmer, your job is to provide solutions to business problems in the most effective, efficient, maintainable way possible...don't get so hung up on all the "rules" and "regulations" of OOP...objects arn't the only option.

                    J Offline
                    J Offline
                    James Lonero
                    wrote on last edited by
                    #167

                    Interesting. I thought that C# originally was to be more OO than C++. Even in C++, you can write a completely procedural language type program (the C language). Maybe, Microsoft, in their zeal to make it easier to write software, is turning C# into an all in one language where you can get a job done any way you want. Maybe, at some later date, the keyword class will not be deprecated (not a first class item). Already, the anonymous type and var keyword are reducing the OO aspect of the language. Then, maybe, the hardcore OO engineers will move to Java.

                    P J S 3 Replies Last reply
                    0
                    • J Jon Rista

                      They absolutely do! Look at IEnumerable...EVERY type that implements IEnumerable DOES INDEED get the full functionality of all extension methods written for IEnumerable (so long as the proper using statement(s) are included). You don't have to "implement" the extension methods on each class that implements IEnumerable...the extension methods absolutely do add new functionality without you having to do any extra implementation. And that functionality is accessed through class INSTANCES...not static methods or utility types. You anti-progressive types drive me nuts sometimes...get off your high horse and USE the tools at your disposal. You might find that you actually like them.

                      P Offline
                      P Offline
                      Pawel Krakowiak
                      wrote on last edited by
                      #168

                      Personally I love the extensions methods for the collection types, like List[^]. They provide some very powerful and useful ways to manipulate data. It's a big productivity improvement, IMO.

                      P 1 Reply Last reply
                      0
                      • P PIEBALDconsult

                        Here here! var should only be used when you don't know the type!

                        J Offline
                        J Offline
                        Jon Rista
                        wrote on last edited by
                        #169

                        Perhapse that should be worded "can't" know the type...as in the case of anonymous types. Its easy enough to debug and find out a type you don't know. Var has its uses, but like almost any language feature, it can be missused. I think rather than restricting its use, though, better educating our programmers and instilling good practices is the first thing we should try. ;)

                        J P 2 Replies Last reply
                        0
                        • B bwilhite

                          Design by Contract. There's support for it in one of those little extra languages that they fiddle around with, but I'd like to see support (language-level? just a library?) for it in C#.

                          J Offline
                          J Offline
                          Jon Rista
                          wrote on last edited by
                          #170

                          I agree, I think Spec# should be integrated into C# 4.0. Design by Contract is better than just adding support for const. I want all my contractual features...function purity, non-null parameters, input requirements and output ensures, etc. I can't wait for the day when my code is not only well written, but contractually secure.

                          1 Reply Last reply
                          0
                          • Y Yortw

                            1. Retry keyword, from VB.NET (structured error handling) 2. Dyanmic intefaces, from VB.NET 3. AppActivate function, from VB.NET 4. Non-beta version of the parallel task library 5. Better WPF designers 6. Better user experience when working on single code file shared between .NET Framework and .NET Compact Framework projects 7. Improved keyboard/focus and dynamic control creation support in .NET Compact Framework (support for ActiveControl, ControlAdded/Removed events etc). 8. Fix for the (very rare) bug caused by compiler optimisations on the String.IsNullOrEmpty function. 9. A version of the various TryParse functions that returns the default value for expected type, instead of returning true/false with an out parameter. 10. TryParse on System.Enum. Probably a lot of other stuff too, but that's all I can think of off the top of my head :-D Tuples would also be cool :cool:

                            J Offline
                            J Offline
                            Jon Rista
                            wrote on last edited by
                            #171

                            @4-10, were talking C# the language, version 4.0. Your points 4-10 are all framework features, not language features.

                            Y 1 Reply Last reply
                            0
                            • J James Lonero

                              Interesting. I thought that C# originally was to be more OO than C++. Even in C++, you can write a completely procedural language type program (the C language). Maybe, Microsoft, in their zeal to make it easier to write software, is turning C# into an all in one language where you can get a job done any way you want. Maybe, at some later date, the keyword class will not be deprecated (not a first class item). Already, the anonymous type and var keyword are reducing the OO aspect of the language. Then, maybe, the hardcore OO engineers will move to Java.

                              P Offline
                              P Offline
                              Pawel Krakowiak
                              wrote on last edited by
                              #172

                              I think that the extension methods resemble more of a dynamic language features rather than procedural programming. You still need to have an object instance to call on such method and they are created for only the particular type. So an extension method added to the String class cannot be called from anything that is not a string. I think Microsoft is looking for a more dynamic language and extension methods work a little like JavaScript where you can attach new methods and properties to an existing object, but in C# it is still static and strong typing is preserved. I know you people whine about the fact that using the extension methods I don't inherit from the said class... Sometimes you want to only add a single method, perhaps it's laziness (not good). Good thing is that in order to make your extension methods work you must put the using keyword in the file where you plan to use them. Moreover - extension method don't just float there, they themselves must be contained in a static class. So what is the difference between creating a utility class with static methods like you would do in C# 2.0 and creating a static class with extension methods in C# 3.0? In the latter case you get cleaner syntax, being able to call the methods on the object directly, rather than passing it to a utility class method to get the same result. All in all, I understand the concerns, but I just couldn't resist the productivity boost it gave me the first time I saw extension methods.

                              J 1 Reply Last reply
                              0
                              • J Jon Rista

                                Perhapse that should be worded "can't" know the type...as in the case of anonymous types. Its easy enough to debug and find out a type you don't know. Var has its uses, but like almost any language feature, it can be missused. I think rather than restricting its use, though, better educating our programmers and instilling good practices is the first thing we should try. ;)

                                J Offline
                                J Offline
                                James Lonero
                                wrote on last edited by
                                #173

                                Jon, you can educate the programmers until you're blue in the face. But, when crunch time comes and all hell breaks loose, then we all take the quick and easy way out. Once you get used to using var (as with any shortcut), you'll continue using it. Usually, the best way to prevent using it (in a company or an organization) is to specifically disallow it in the coding standards and check for it in the code reviews.

                                1 Reply Last reply
                                0
                                • P Pawel Krakowiak

                                  I think that the extension methods resemble more of a dynamic language features rather than procedural programming. You still need to have an object instance to call on such method and they are created for only the particular type. So an extension method added to the String class cannot be called from anything that is not a string. I think Microsoft is looking for a more dynamic language and extension methods work a little like JavaScript where you can attach new methods and properties to an existing object, but in C# it is still static and strong typing is preserved. I know you people whine about the fact that using the extension methods I don't inherit from the said class... Sometimes you want to only add a single method, perhaps it's laziness (not good). Good thing is that in order to make your extension methods work you must put the using keyword in the file where you plan to use them. Moreover - extension method don't just float there, they themselves must be contained in a static class. So what is the difference between creating a utility class with static methods like you would do in C# 2.0 and creating a static class with extension methods in C# 3.0? In the latter case you get cleaner syntax, being able to call the methods on the object directly, rather than passing it to a utility class method to get the same result. All in all, I understand the concerns, but I just couldn't resist the productivity boost it gave me the first time I saw extension methods.

                                  J Offline
                                  J Offline
                                  Jon Rista
                                  wrote on last edited by
                                  #174

                                  Agreed, extension methods arn't really procedural programming, but they arn't object oriented either. They DO definitely have a place, and DO definitely provide useful value when used properly. Same goes for the var keyword...it has its uses, and considering that it is local-scoped, the range of missuse of var is very, very limited. I used to be a hard-core, object-oriented purist. It was only when I finally let go if my bias that I realized the freedom one can have when you take full and proper advantage of a language like C#. Correctly used, C# is probably the most powerful, effective language on the planet for efficiently providing solutions to business problems...and that, ultimately, is what we programmers are here for...providing solutions.

                                  1 Reply Last reply
                                  0
                                  • J James Lonero

                                    Interesting. I thought that C# originally was to be more OO than C++. Even in C++, you can write a completely procedural language type program (the C language). Maybe, Microsoft, in their zeal to make it easier to write software, is turning C# into an all in one language where you can get a job done any way you want. Maybe, at some later date, the keyword class will not be deprecated (not a first class item). Already, the anonymous type and var keyword are reducing the OO aspect of the language. Then, maybe, the hardcore OO engineers will move to Java.

                                    J Offline
                                    J Offline
                                    Jon Rista
                                    wrote on last edited by
                                    #175

                                    C# is what I call a progressive language. It started out in a very simple, Java-like form in v1.0. But it has continually evolved into a richer, stronger, more expressive language that has only served to do one thing: Improve my productivity. Hard-core OO programming is a very limiting form of software engineering. Objects don't solve everything in the simplest way...on the contrary, rich object models with full inheritance and associative relationships can get in the way of providing a simple, effective, easily maintained solution. You have to use the right tool for the job, and objects are most assuredly NOT the right tool for every job. I for one am extremely grateful that Microsoft did not allow C# to stagnate like Sun allowed Java to. I use C# for what it is...a progressive, evolving language that has an EXTENSIVE amount of analysis and design behind it to ensure that features that are added provide benefit...not detriment. The end result, IMO, is an extremely powerful, expressive, flexible language that allows me to quickly solve problems without always having to resort to a complex OO mechanism. Sometimes, an enumerable collection of simple structures (tuples say), is all one needs to get the job done.

                                    P 1 Reply Last reply
                                    0
                                    • J Jon Rista

                                      Perhapse this (.NET 3.5 IEnumerable extensions): int[] supportedValues = new int[] {3,4,5}; int x = 4; if (supportedValues.Any(v => v == x)) { // Do something }

                                      S Offline
                                      S Offline
                                      SlingBlade
                                      wrote on last edited by
                                      #176

                                      The idea is so good they already implemented it in 3.5! ;P Perhaps I should stop using 2.0. I played with 3.5 briefly to check out WPF and Linq and didn't particularly see much use for them so I decided to stay away because of the performance drawbacks that came with WPF and didn't want to be tempted to use it. I missed the IEnumerable extensions and probably many more features that could come in handy. Am I the only one that WPF runs like molasses for? If not are there any other features to stay away from in order to perform decent on lowend and older machines? P.S. - Thanks for the Line Counter add-in! I've been using it for a couple months now.

                                      modified on Friday, October 3, 2008 2:30 AM

                                      J 1 Reply Last reply
                                      0
                                      • J Jon Rista

                                        I think what your asking for can be fairly closely achieved already in C# 3.0..its just slightly more verbose: int[] tupleFunc() { double w, h, d; // ... return new[] { w, h, d }; } int[] tuple = tupleFunc();

                                        J Offline
                                        J Offline
                                        Jon Rista
                                        wrote on last edited by
                                        #177

                                        On the flip side, native tuples in C# would be nice: public [int,int] MinMax(IEnumerable numbers) { int min, max; // Compute min and max return tuple[min,max]; } tuple[int,int] result = MinMax(new[] { 1, 2, 3, 5, 8, 13 }); int first = result[0]; A more complex example with an "anonymous" tuple might be: public [int,string,string,DateTime] TupleFunc() { return tuple[1,"String1","String2",DateTime.Now]; } tuple result = TupleFunc(); int num = result[0]; string first = result[1]; //...

                                        1 Reply Last reply
                                        0
                                        • J Jamie Nordmeyer

                                          So now that C# 4.0 is being talked about, I was wondering what people thought would be good additions to the language. Sorry if this is a repost, but I went through several pages, and didn't see anything, so... What I'd frankly love to see would be tuples. Rather than having to use multiple 'out' parameters, you'd just return multiple values:

                                          public int,int MinMax(int[] numbers)
                                          {
                                          int min, max;
                                          // Code to calculate min/max

                                          return min, max;
                                          }

                                          What do you think? What would be good for the next version?

                                          Kyosa Jamie Nordmeyer - Taekwondo Yi (2nd) Dan Portland, Oregon, USA

                                          R Offline
                                          R Offline
                                          rcollina
                                          wrote on last edited by
                                          #178

                                          The ability to include directly MSIL in code. Not strictly necessary but I'd love to be able to. Be it for method bodies or to describe MSIL streams (anyone using Emit knows what I'm talking about). Contracts. Oh they would be so nice :)

                                          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