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 458 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.
  • J Jon Rista

    I'm still not convinced that extension methods are this evil black sheep. Were beyond issues of portability now, and into issues of coding preference, I think. a) Package extension methods in exclusive namespaces. aa) Where would you package them, and why would that place be better than an exclusive namespace? b) Extension methods usually implement an algorithm. bb) First off, implementation of the method isn't the point, its the feature itself. Second, don't all methods implement an algorithm, however simple that algorithm may be? c) Don't tell anyone else how to properly use it. cc) Who defines what proper use is? In what usage instances is one way proper, and what other instances is it improper? Again, I think a little common sense works here. Extension method best practice #1: SIDE EFFECT FREE. Follow that rule, and I think your use of extension methods will be quite enjoyable, regardless of where they are packaged or whether they implement an algorithm or....well, isn't that it...algorithms? Another interesting tidbit about C# 3.0/.NET 3.5. Since .NET 3.5 is just a bunch of new API's on top of the .NET 2.0 runtime, and C# is a translator as well as a compiler, the end result is still CLI that is compatible with .NET 2.0. So long as the appropriate assemblies are available, a .NET application written with C# 3.0/.NET 3.5 should run on a system with only .NET 2.0 installed. Sounds pretty portable to me. ;) Speaking of goto, I use it in two cases:

    foreach (...)
    {
    foreach (...)
    {
    foreach (...)
    {
    if (exitCondition)
    goto DoneWithLoops;
    }
    }
    }

    DoneWithLoops:
    // Finish up

    Thats a lot cleaner than having a bunch of flags that have to be checked in every loop if a complete exit from all loops is needed. C# translates complete exits from nested loops into a goto anyway in a lot of cases, so the above code is whats going to happen anyway.

    switch (...)
    {
    case 1:
    {
    // Do something that augments default
    goto default;
    }
    case 2:
    {
    // Do something unique
    break;
    }
    default:
    {
    // Do common stuff
    break;
    }
    }

    S Offline
    S Offline
    Sunny Ahuwanya
    wrote on last edited by
    #211

    aa) If I didn't notice Microsoft placed all related extension methods in an (almost) extension-method only namespace. I would be placing regular methods and etension methods in the same namespace.

    Jon Rista wrote:

    b) Extension methods usually implement an algorithm. bb) First off, implementation of the method isn't the point, its the feature itself. Second, don't all methods implement an algorithm, however simple that algorithm may be?

    I mean most LINQ extension methods implement a generic algorithm that works with any object as opposed to a function that performs an action on one object. On most blogs i've read, developers want to extend a type with a function they want so badly instead of considering deriving from that type and adding the function. cc) Since Microsoft developed this feature and must have researched it intensively, they should have at least warned us about it.

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

    J 1 Reply Last reply
    0
    • J Jamie Nordmeyer

      I saw someone comment on that on another forum. Basically, you'd have something like this (using his sample syntax):

      int? x = Company?.Person["Bob"]?.Age;

      If Company or Company.Person["Bob"] were null, then x would be set to null, rather than getting an exception. I likes.

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

      K Offline
      K Offline
      Ken_GHill
      wrote on last edited by
      #212

      no more null refs!!!!

      M 1 Reply Last reply
      0
      • J Jon Rista

        Glad you like the Line Counter add-in. I've been poking at it lately, trying to improve it and make it work with VS2008 too. Hopefully another version will be released soon. As for C# 3.0/.NET 3.5, there are LOTS of useful things. WPF is certainly more resource heavy than basic windows forms, but its only one of the many new things available. You also have WCF, WF, LINQ (which isn't just for querying databases...it queries any enumerable type which is GREAT, you'll love it), anonymous types, partial methods, expression trees, class initializers, HashSet, and more. The LINQ features, which is where IEnumerable.Any comes from...its a part of LINQ, are probably the most useful addition to the language.

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

        Yeah, I'll definately have to upgrade to VS2008 and start using the new stuff. That's cool that you have been poking at the line counter. I wouldn't mind seeing a toolbar added and the ability to calculate the contents of a folder. Calculating basedon namespaces, classes, interfaces etc. would be nice too but I imagine that would be a lot more work than folders.

        1 Reply Last reply
        0
        • P PIEBALDconsult

          Jon Rista wrote:

          should be worded "can't"

          Yes, but for me they're pretty much equivalent; if I can know it I do know it. Unfortuntely there are some who can know it but are too darn lazy to find out.

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

          By "can't" I really meant can't. There IS no type for an anonymous type at design time...only at runtime. In that case, use of var is the only possability. You physically can't know the type.

          P 1 Reply Last reply
          0
          • J Jon Rista

            By "can't" I really meant can't. There IS no type for an anonymous type at design time...only at runtime. In that case, use of var is the only possability. You physically can't know the type.

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #215

            Yes, we agree on that.

            1 Reply Last reply
            0
            • S Sunny Ahuwanya

              aa) If I didn't notice Microsoft placed all related extension methods in an (almost) extension-method only namespace. I would be placing regular methods and etension methods in the same namespace.

              Jon Rista wrote:

              b) Extension methods usually implement an algorithm. bb) First off, implementation of the method isn't the point, its the feature itself. Second, don't all methods implement an algorithm, however simple that algorithm may be?

              I mean most LINQ extension methods implement a generic algorithm that works with any object as opposed to a function that performs an action on one object. On most blogs i've read, developers want to extend a type with a function they want so badly instead of considering deriving from that type and adding the function. cc) Since Microsoft developed this feature and must have researched it intensively, they should have at least warned us about it.

              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
              #216

              aaa) I prefer having them in their own namespace. That forces you to think about using them. To support your argument, it forces you to do something that will cause a "ported" app break at compile time if that extensions namespace isn't available. It also allows you to interchange extensions that do the same thing. If you decide you can do better than Microsoft and write the same IEnumerable extensions, that produce the same results, but perform faster...since they are in a different namespace, you can! Extension Method Best Practices[^] In regards to inheriting to extend functionality. Inheritance is good only to a certain degree, and is not always the appropriate answer. For one, there is the ongoing Composition vs. Inheritance debate. Two, deep inheritance chains are difficult to maintain and manage. Three, your not always looking create a whole new type. You just need more functionality on an existing type. The beauty of extension methods is, if you DO inherit from an extended type, your extensions are available on all derived types too. The only real caveat with extension methods is the possible future inclusion of a similar method name on the extended class. I havn't figured that one out yet, but I doubt I'll completely give up on extension methods because of one possible problem. Having extension methods replaced with a native method isn't necessarily a bad thing, either. For example, I have an extention method that determines if an ObjectContext for Entity Framework "contains" an entity. The result is either true or false...and the rules that determine that are static. I don't care if the implementation comes from my extension or a native implementation...I just need to know the result.

              S 1 Reply Last reply
              0
              • J Jon Rista

                aaa) I prefer having them in their own namespace. That forces you to think about using them. To support your argument, it forces you to do something that will cause a "ported" app break at compile time if that extensions namespace isn't available. It also allows you to interchange extensions that do the same thing. If you decide you can do better than Microsoft and write the same IEnumerable extensions, that produce the same results, but perform faster...since they are in a different namespace, you can! Extension Method Best Practices[^] In regards to inheriting to extend functionality. Inheritance is good only to a certain degree, and is not always the appropriate answer. For one, there is the ongoing Composition vs. Inheritance debate. Two, deep inheritance chains are difficult to maintain and manage. Three, your not always looking create a whole new type. You just need more functionality on an existing type. The beauty of extension methods is, if you DO inherit from an extended type, your extensions are available on all derived types too. The only real caveat with extension methods is the possible future inclusion of a similar method name on the extended class. I havn't figured that one out yet, but I doubt I'll completely give up on extension methods because of one possible problem. Having extension methods replaced with a native method isn't necessarily a bad thing, either. For example, I have an extention method that determines if an ObjectContext for Entity Framework "contains" an entity. The result is either true or false...and the rules that determine that are static. I don't care if the implementation comes from my extension or a native implementation...I just need to know the result.

                S Offline
                S Offline
                Sunny Ahuwanya
                wrote on last edited by
                #217

                Jon Rista wrote:

                Extension Method Best Practices[^]

                Thanks for that link.

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

                1 Reply Last reply
                0
                • V Vikram A Punathambekar

                  Yeah, that's how I thought it would be implemented, if it were.

                  S. Senthil Kumar wrote:

                  in C++, I hated the cascading effect of const

                  I can't see how you could make it non-cascading: if a const method were to call a non-const method (which then proceeds to modify the object), that would totally break the contract it promises its calling methods.

                  S. Senthil Kumar wrote:

                  the throws clause of every method that directly or indirectly calls it will have to modified

                  Only if the excception is not handled. I am a big fan of Java's checked exceptions. :)

                  Cheers, Vıkram.


                  "You idiot British surprise me that your generators which grew up after Mid 50s had no brain at all." - Adnan Siddiqi.

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

                  Vikram A Punathambekar wrote:

                  Only if the excception is not handled.

                  True, but isn't that the typical case? I generally find that the exception handling part is usually several layers above the throwing part.

                  Vikram A Punathambekar wrote:

                  I am a big fan of Java's checked exceptions.

                  Is it because of the documentary value (listing of all possible exceptions that could be thrown by a method)?

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

                  V 1 Reply Last reply
                  0
                  • S S Senthil Kumar

                    Vikram A Punathambekar wrote:

                    Only if the excception is not handled.

                    True, but isn't that the typical case? I generally find that the exception handling part is usually several layers above the throwing part.

                    Vikram A Punathambekar wrote:

                    I am a big fan of Java's checked exceptions.

                    Is it because of the documentary value (listing of all possible exceptions that could be thrown by a method)?

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

                    V Offline
                    V Offline
                    Vikram A Punathambekar
                    wrote on last edited by
                    #219

                    S. Senthil Kumar wrote:

                    Is it because of the documentary value

                    Partly. I like better the fact that it forces developers to handle exceptions, or at least advertise them so the calling code will. It also means your app will almost certainly never crash due to a checked exception being thrown. But the best of intentions of the language designer can be undone by wilful wrongdoing by the developer: I have seen far too many methods where all the code is inside a try block, followed by an empty catch all block :wtf: ; or a method that throws a few specific checked exceptions but has the signature void functionName(int someParam) throws Exception. :((

                    Cheers, Vıkram.


                    "You idiot British surprise me that your generators which grew up after Mid 50s had no brain at all." - Adnan Siddiqi.

                    1 Reply Last reply
                    0
                    • J Jon Rista

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

                      Y Offline
                      Y Offline
                      Yortw
                      wrote on last edited by
                      #220

                      Sorry, that is true... except some of them are IDE features and not .NET ones :)

                      1 Reply Last reply
                      0
                      • P PIEBALDconsult

                        Yortw wrote:

                        8. Fix for the (very rare) bug caused by compiler optimisations on the String.IsNullOrEmpty function.

                        I thought they already fixed that in 3.0 or 3.5.

                        Y Offline
                        Y Offline
                        Yortw
                        wrote on last edited by
                        #221

                        Last time I checked the bug report on connect.microsoft.com they had marked it as closed, "Won't Fix"... and I thought that was after 3.5 was released, but I could be wrong.

                        1 Reply Last reply
                        0
                        • P PIEBALDconsult

                          Yortw wrote:

                          8. Fix for the (very rare) bug caused by compiler optimisations on the String.IsNullOrEmpty function.

                          I thought they already fixed that in 3.0 or 3.5.

                          Y Offline
                          Y Offline
                          Yortw
                          wrote on last edited by
                          #222

                          Sorry, you are correct, they fixed it in 'orcas'.

                          1 Reply Last reply
                          0
                          • C Christian Graus

                            I'd love to be able to check if say, myObject was null and if it was, return a result, and if not, return a property of myObject using the ?? operator.

                            Christian Graus No longer a Microsoft MVP, but still happy to answer your questions.

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

                            Actually, I think the whole problem would be better solved by lifting the . operator in the same way they did for some of the other operators to handle nullable types. It is essentially making nullability a true first-class language citizen, whereby accessing a property or calling a function on a null object simply returns null rather than a NullReferenceException.

                            Scott Dorman

                            Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                            Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                            1 Reply Last reply
                            0
                            • J Jamie Nordmeyer

                              And I agree. Learn how to use what you have first. And I've used the Pair object before. But being able to specify a list of return values would be nice. Not necessary, no. But nice. The same thing could be said for the ?? operator though. Do you need it? No. But it's definitely nice! :)

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

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

                              Tuple support is certainly nice but there are other ways to handle this. Simply having some predefined Tuple<T> type classes like we have with Func<T> and Action<T> would be more than sufficient, I think.

                              Scott Dorman

                              Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                              Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                              1 Reply Last reply
                              0
                              • C Christian Graus

                                I'd love to see a const keyword on parameters to methods, and optional parameters. Both of which seem simple enough.

                                Christian Graus No longer a Microsoft MVP, but still happy to answer your questions.

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

                                Optional parameters will probably be there. Const paramters are doubtful although it would be nice, at least as a compile-time check.

                                Scott Dorman

                                Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                1 Reply Last reply
                                0
                                • G Giampaolo Papotti

                                  I strongly Agree! C# cut-offs from c++ were really too deep. cons keyword (both on parameters and members signatures) shoud be a MUST in any oo language. And what about the annoying lack of default in parameters? I'd like to see c# designers and gurus dealing with Office PIA... I'm sure they would have a private build of csc.exe with default parameters implementeed .... InvokeExcelStuff(theOnlyNeededParameter, null, null, null, null, null, null, null, null, null, null, null, null, null, null....)

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

                                  Giampaolo Papotti wrote:

                                  And what about the annoying lack of default in parameters? I'd like to see c# designers and gurus dealing with Office PIA... I'm sure they would have a private build of csc.exe with default parameters implementeed .... InvokeExcelStuff(theOnlyNeededParameter, null, null, null, null, null, null, null, null, null, null, null, null, null, null....)

                                  This should become simpler...stay tuned.

                                  Scott Dorman

                                  Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                  Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                  1 Reply Last reply
                                  0
                                  • S Sunny Ahuwanya

                                    There are so many things wrong with extension methods that I *still* get baffled how the geniuses at M$ included that as a feature. I guess LINQ must have been a HUGE thing for every team to bend their libraries and languages to 'force' it to fit in. I just want the option not to use it or make me use it in the "good way". This is just like the way you could set option strict in classic VB. Luckily almost all Microsoft extension methods come with in their exclusive namespaces. So all I have to do now is not include those namespaces BUT that doesn't prevent some other genius at XYZ company to pack extension methods with regular methods in their libraries and forcing ME to write bad code. Chip on my shoulder :)

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

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

                                    Extension methods are just like any other language feature...they have the ability to be misused/abused (and not just from newbies, but by anyone). I don't think that's a good reason to not include a feature or we would end up writing assembly again. How do extension methods force you to write bad code? If you don't want to use them, don't use them. It's that simple. Yes, there should be more guidance on how to properly use/write extension methods (which is coming) and possibly some better compiler support to enforce that. I disagree with the ability to add extension methods in the same namespace as one that's defined by Microsoft. This isn't actually polluting a namespace but rather polluting a type, but that's kind of the idea behind extension methods. BTW, other languages have similar features as well and are usually called Mix-Ins. The thing to remember about extension methods is that they are nothing more than an alternate syntax for calling a static method on a static class. They are defined in exactly the same way (with the addition of the "this" keyword in the parameter list) and compile to the exact same IL as if you were to call it the "normal" way (i.e., as a static method on a static class and pass in the object you want to modify/act on). Calling it as an extension is a more natural syntax, but it's all syntax sugar/compiler magic. Extension methods do not have access to the internal state or variables of the class they are extending. You also can't use an extension method with the same signature as a native method...you can declare one but there is no way to actually override the native method with your extension and it won't show up as an available method in intellisense so there is no way to call it except as a static method on a static class, in which case you no longer have the extension syntax and it's completely clear which method is being called.

                                    Scott Dorman

                                    Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                    Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                    1 Reply Last reply
                                    0
                                    • P PIEBALDconsult

                                      And an ability to know what version is being used, to enable conditional compilation in a standard way:

                                      public static string F
                                      (

                                      **# if VERSION>=3.5
                                      this

                                      endif**

                                      string S
                                      

                                      )
                                      {
                                      ...
                                      }

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

                                      That would be very nice to have.

                                      Scott Dorman

                                      Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                      Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                      1 Reply Last reply
                                      0
                                      • U User 3973690

                                        A couple of things I would like is better control over memory. The automatic garbage collection is nice and I understand that it's usualy better just to let it be so it can collect when needed, but in some cases I know the memory can and must be freed like when processing a large import file. Also I would like to be able to "Destroy" an object in certain situations. By that I mean to have one method that can nullify all refrences to a particualar object. Another thing would be multipule inheritance, or at least some psuedo-composite type scenario. My company seels a website management tool which runs as a smart client, so I write a lot of UI code that is shared between web and windows. We have our own MVC style system so much of the "Controller" and "Model" code is common to both web and win, but we also have several methods we have to add to both web and windows controls to support that system. Our only option now is to use interfaces, but 90% of the implementation of those interfaces for each control could be shared, but is currently copied since both our web and windows controls can't derive off of a base class.

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

                                        Member 3976638 wrote:

                                        A couple of things I would like is better control over memory. The automatic garbage collection is nice and I understand that it's usualy better just to let it be so it can collect when needed, but in some cases I know the memory can and must be freed like when processing a large import file. Also I would like to be able to "Destroy" an object in certain situations. By that I mean to have one method that can nullify all refrences to a particualar object.

                                        In .NET, nulling an object does not release/free any memory used by that object. In your example of processing a large import file, a lot of how you interact with the file will determine the memory used, but if you're using streams at all you should be disposing of those streams when you are finished with them. Also, keep in mind that if you load the entire file into memory at once and the resulting object is over 85K in size it's ending up on the large object heap which has different rules with respect to how the GC runs. If you absolutely need to reclaim the memory, you can call GC.Collect(int generation, GCCollectionMode mode) overload and use a GCCollectionMode.Optimized, which will only run the collection if the GC determines it is needed or GCCollectionMode.Forced, which will force a collection. If you do things like this, you need to be very careful about it as every time you run a collection cycle your application's main thread (and any threads it creates) will be frozen during the cycle.

                                        Scott Dorman

                                        Microsoft® MVP - Visual C# | MCPD President - Tampa Bay IASA [Blog][Articles][Forum Guidelines]


                                        Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai

                                        1 Reply Last reply
                                        0
                                        • K Ken_GHill

                                          no more null refs!!!!

                                          M Offline
                                          M Offline
                                          mvonballmo
                                          wrote on last edited by
                                          #230

                                          There is an extension of C# available that provides some help in this area: spec#. I haven't used it myself, but I'm a big fan of Eiffel, which has deep design-by-contract support. Spec# includes notation to indicate that a variable or parameter can never be null. BTW, if you're really interested in further reading on features for C#, the Eiffel language is a good place to start, as a language that has true generics since inception as well as tuples, anchored types, parameter covariance and many other interesting goodies.

                                          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