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. Fave Operator of the Day

Fave Operator of the Day

Scheduled Pinned Locked Moved The Lounge
csharpc++comarchitecturequestion
55 Posts 26 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.
  • C Chris Maunder

    The C# 2.0 null coalescing operator ?? God bless its little cotton socks.

    cheers, Chris Maunder

    CodeProject.com : C++ MVP

    L Offline
    L Offline
    leppie
    wrote on last edited by
    #12

    jmp Allows you to jump from function to function :)

    xacc.ide
    IronScheme a R5RS-compliant Scheme on the DLR
    The rule of three: "The first time you notice something that might repeat, don't generalize it. The second time the situation occurs, develop in a similar fashion -- possibly even copy/paste -- but don't generalize yet. On the third time, look to generalize the approach."

    1 Reply Last reply
    0
    • N Nish Nishant

      Jim Crafton wrote:

      You tease - don't blue-ball us, give up an example!!!

      return _cachedItem ?? (_cachedItem = GetItem());

      Regards, Nish


      Nish’s thoughts on MFC, C++/CLI and .NET (my blog)
      My latest book : C++/CLI in Action / Amazon.com link

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #13

      I would have like a ??= operator too, for exactly what you are showing. Personally, I find it more handy with dealing with optionals.

      xacc.ide
      IronScheme a R5RS-compliant Scheme on the DLR
      The rule of three: "The first time you notice something that might repeat, don't generalize it. The second time the situation occurs, develop in a similar fashion -- possibly even copy/paste -- but don't generalize yet. On the third time, look to generalize the approach."

      1 Reply Last reply
      0
      • M M dHatter

        NERDS! :cool:

        M Offline
        M Offline
        Mustafa Ismail Mustafa
        wrote on last edited by
        #14

        and proud! :cool:

        "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook "There is no wealth like knowledge, no poverty like ignorance." Ali ibn Abi Talib "Animadvertistine, ubicumque stes, fumum recta in faciem ferri?"

        1 Reply Last reply
        0
        • J Jim Crafton

          You tease - don't blue-ball us, give up an example!!! :)

          ¡El diablo está en mis pantalones! ¡Mire, mire! Real Mentats use only 100% pure, unfooled around with Sapho Juice(tm)! SELECT * FROM User WHERE Clue > 0 0 rows returned Save an Orange - Use the VCF! VCF Blog

          S Offline
          S Offline
          Steve Hansen
          wrote on last edited by
          #15

          Also easy when working with strings. string result = someString ?? string.Empty;

          1 Reply Last reply
          0
          • C Chris Maunder

            The C# 2.0 null coalescing operator ?? God bless its little cotton socks.

            cheers, Chris Maunder

            CodeProject.com : C++ MVP

            H Offline
            H Offline
            Howard Richards
            wrote on last edited by
            #16

            Aha.. so when is CodeProject being upgrade to 3.5 then ? ;)

            'Howard

            1 Reply Last reply
            0
            • C Chris Maunder

              The C# 2.0 null coalescing operator ?? God bless its little cotton socks.

              cheers, Chris Maunder

              CodeProject.com : C++ MVP

              P Offline
              P Offline
              Pete OHanlon
              wrote on last edited by
              #17

              For the really nerdy:

              string value = value1 ?? value2 ?? value3 ?? finalDefaultValue;
              

              Deja View - the feeling that you've seen this post before.

              My blog | My articles

              G L 2 Replies Last reply
              0
              • P Pete OHanlon

                For the really nerdy:

                string value = value1 ?? value2 ?? value3 ?? finalDefaultValue;
                

                Deja View - the feeling that you've seen this post before.

                My blog | My articles

                G Offline
                G Offline
                Gary Wheeler
                wrote on last edited by
                #18

                OK. For us poor, ignorant C++ jocks, please explain what that abomination does. I'm guessing it's something like this:

                if (value1 != NULL) value = value1;
                else if (value2 != NULL) value = value2;
                else if (value3 != NULL) value = value3;
                else value = finalDefaultValue;


                Software Zen: delete this;

                P 1 Reply Last reply
                0
                • G Gary Wheeler

                  OK. For us poor, ignorant C++ jocks, please explain what that abomination does. I'm guessing it's something like this:

                  if (value1 != NULL) value = value1;
                  else if (value2 != NULL) value = value2;
                  else if (value3 != NULL) value = value3;
                  else value = finalDefaultValue;


                  Software Zen: delete this;

                  P Offline
                  P Offline
                  Pete OHanlon
                  wrote on last edited by
                  #19

                  Yup - that's exactly what it does - it coalesces through the chain until it finds a none-null value.

                  Deja View - the feeling that you've seen this post before.

                  My blog | My articles

                  G 1 Reply Last reply
                  0
                  • P Pete OHanlon

                    Yup - that's exactly what it does - it coalesces through the chain until it finds a none-null value.

                    Deja View - the feeling that you've seen this post before.

                    My blog | My articles

                    G Offline
                    G Offline
                    Gary Wheeler
                    wrote on last edited by
                    #20

                    I'm curious. Does this pattern occur often enough in .NET programming that it was worth adding an operator for it? Or is it the case that, since the operator is available, you use that pattern more often?


                    Software Zen: delete this;

                    D R 2 Replies Last reply
                    0
                    • G Gary Wheeler

                      I'm curious. Does this pattern occur often enough in .NET programming that it was worth adding an operator for it? Or is it the case that, since the operator is available, you use that pattern more often?


                      Software Zen: delete this;

                      D Offline
                      D Offline
                      Daniel Grunwald
                      wrote on last edited by
                      #21

                      I use ?? from time to time, but I needed more than a single ?? in an expression. I think a "?." operator would be much more useful than ??. "obj?.Method()" could be syntax sugar for "(obj != null) ? obj.Method() : null" (except that "obj" is evaluated only once). Hopefully MS will add something like that to C# 4.0...

                      1 Reply Last reply
                      0
                      • G Gary Wheeler

                        I'm curious. Does this pattern occur often enough in .NET programming that it was worth adding an operator for it? Or is it the case that, since the operator is available, you use that pattern more often?


                        Software Zen: delete this;

                        R Offline
                        R Offline
                        Rocky Moore
                        wrote on last edited by
                        #22

                        Gary Wheeler wrote:

                        Does this pattern occur often enough in .NET

                        In normal code, there is often times you want to get a value back, even if it is a specific default value rather than having to deal with nulls. Now that there is nullable types, it happens quite a bit more. While I am not sure that there is a need for a chain of values as mentioned in the prior post, the ?? is handy to have around.

                        Rocky <>< Blog Post: LINQ Scores a Yahtzee! Tech Blog Post: Cheap Biofuels and Synthetics coming soon?

                        1 Reply Last reply
                        0
                        • P Pete OHanlon

                          For the really nerdy:

                          string value = value1 ?? value2 ?? value3 ?? finalDefaultValue;
                          

                          Deja View - the feeling that you've seen this post before.

                          My blog | My articles

                          L Offline
                          L Offline
                          leppie
                          wrote on last edited by
                          #23

                          Ok, so we comparing nerdiness, beat this one for flavour :)

                          class Foo
                          {
                          CallTargetWithContext0 target0;
                          CallTargetWithContext1 target1;
                          CallTargetWithContext2 target2;
                          CallTargetWithContext3 target3;
                          CallTargetWithContext4 target4;
                          CallTargetWithContext5 target5;
                          CallTargetWithContextN targetN;

                          public Foo(Delegate target)
                          {
                          target =
                          (target0 = target as CallTargetWithContext0) ??
                          (target1 = target as CallTargetWithContext1) ??
                          (target2 = target as CallTargetWithContext2) ??
                          (target3 = target as CallTargetWithContext3) ??
                          (target4 = target as CallTargetWithContext4) ??
                          (target5 = target as CallTargetWithContext5) ??
                          // for some reason the last one needs a cast...
                          ((Delegate)(targetN = target as CallTargetWithContextN));
                          }
                          }

                          xacc.ide
                          IronScheme a R5RS-compliant Scheme on the DLR
                          The rule of three: "The first time you notice something that might repeat, don't generalize it. The second time the situation occurs, develop in a similar fashion -- possibly even copy/paste -- but don't generalize yet. On the third time, look to generalize the approach."

                          P 1 Reply Last reply
                          0
                          • C Chris Maunder

                            The C# 2.0 null coalescing operator ?? God bless its little cotton socks.

                            cheers, Chris Maunder

                            CodeProject.com : C++ MVP

                            E Offline
                            E Offline
                            Ennis Ray Lynch Jr
                            wrote on last edited by
                            #24

                            I just had to show someone how to use that yesterday. Also remember it was one of the coding questions of the day here a while back. My favorite operator is noop. I would get it on a tag if I wasn't afraid muggles would mispronounce it.


                            Need a C# Consultant? I'm available.
                            Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway

                            1 Reply Last reply
                            0
                            • C Christian Graus

                              yeah, I still from time to time type if (myobj) and then remember.

                              Christian Graus - Microsoft MVP - C++ "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

                              B Offline
                              B Offline
                              Blake Miller
                              wrote on last edited by
                              #25

                              Discovering that C# does not support that, my happy face turned into a sad face :(

                              1 Reply Last reply
                              0
                              • S Shog9 0

                                Personally, i'd have preferred something along the lines of the GNU C "shortcut ternary" operator (which it closely resembles). But then, i'd have liked it if C# interpreted null values as false instead of requiring an explicit comparison... :->

                                ----

                                ...the wind blows over it and it is gone, and its place remembers it no more...

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

                                Frankly, I am getting tired of null reference exceptions. I just wish C#/.NET wouldn't be so finicky about null references. For example the latest issue I had was with a MediaPlayer object, where I close the (possibly) existing player before starting a new one: player.Stop(); player = new MediaPlayer(); ... But if I haven't already created a MediaPlayer I get a freaking null reference exception. Of course I know that I should know better and test player for null, but my point is I don't CARE if player.Stop() fails, it's not going to aversely affect my function at all anyway, and my argument is that I bet in 80-90% of cases, null reference exceptions that slip through in production code probably would work fine if they were simply ignored, like my example above. Who's with me for demanding that null reference exceptions be ignored by default and only thrown in blocks explicitly marked as such! Lol, just a mini-rant. :P

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

                                S E 2 Replies Last reply
                                0
                                • L leppie

                                  Ok, so we comparing nerdiness, beat this one for flavour :)

                                  class Foo
                                  {
                                  CallTargetWithContext0 target0;
                                  CallTargetWithContext1 target1;
                                  CallTargetWithContext2 target2;
                                  CallTargetWithContext3 target3;
                                  CallTargetWithContext4 target4;
                                  CallTargetWithContext5 target5;
                                  CallTargetWithContextN targetN;

                                  public Foo(Delegate target)
                                  {
                                  target =
                                  (target0 = target as CallTargetWithContext0) ??
                                  (target1 = target as CallTargetWithContext1) ??
                                  (target2 = target as CallTargetWithContext2) ??
                                  (target3 = target as CallTargetWithContext3) ??
                                  (target4 = target as CallTargetWithContext4) ??
                                  (target5 = target as CallTargetWithContext5) ??
                                  // for some reason the last one needs a cast...
                                  ((Delegate)(targetN = target as CallTargetWithContextN));
                                  }
                                  }

                                  xacc.ide
                                  IronScheme a R5RS-compliant Scheme on the DLR
                                  The rule of three: "The first time you notice something that might repeat, don't generalize it. The second time the situation occurs, develop in a similar fashion -- possibly even copy/paste -- but don't generalize yet. On the third time, look to generalize the approach."

                                  P Offline
                                  P Offline
                                  Pete OHanlon
                                  wrote on last edited by
                                  #27

                                  Oooh - I like that one. The code is completely impenetrable and adds unnecessary complexity. I like it.:-D

                                  Deja View - the feeling that you've seen this post before.

                                  My blog | My articles

                                  L 1 Reply Last reply
                                  0
                                  • C Chris Maunder

                                    The C# 2.0 null coalescing operator ?? God bless its little cotton socks.

                                    cheers, Chris Maunder

                                    CodeProject.com : C++ MVP

                                    M Offline
                                    M Offline
                                    MrEyes
                                    wrote on last edited by
                                    #28

                                    It is up there, but not equal to the nullable int (not an assignment operator like ??, but a little known feature and useful none the less) int? myNullableInt = null; Console.WriteLine(myNullableInt ?? "Null"); myNullableInt = 1; Console.WriteLine(myNullableInt ?? "Null"); Outputs: null 1

                                    L 1 Reply Last reply
                                    0
                                    • N NormDroid

                                      Jim Crafton wrote:

                                      is there a VB equivalent

                                      Who cares ;)

                                      WPF - Imagineers Wanted Follow your nose using DoubleAnimationUsingPath

                                      B Offline
                                      B Offline
                                      Brian Wildrick
                                      wrote on last edited by
                                      #29

                                      norm .net wrote:

                                      Jim Crafton wrote: is there a VB equivalent Who cares

                                      People in jobs that require the use of VB. >.<

                                      N 1 Reply Last reply
                                      0
                                      • P Pete OHanlon

                                        Oooh - I like that one. The code is completely impenetrable and adds unnecessary complexity. I like it.:-D

                                        Deja View - the feeling that you've seen this post before.

                                        My blog | My articles

                                        L Offline
                                        L Offline
                                        leppie
                                        wrote on last edited by
                                        #30

                                        Pete O`Hanlon wrote:

                                        The code is completely impenetrable and adds unnecessary complexity.

                                        In fact, the code is highly optimized for typesafe assignment. IIRC when I tried to rewrite with if's, the generated IL was a lot more 'verbose'. :)

                                        xacc.ide
                                        IronScheme a R5RS-compliant Scheme on the DLR
                                        The rule of three: "The first time you notice something that might repeat, don't generalize it. The second time the situation occurs, develop in a similar fashion -- possibly even copy/paste -- but don't generalize yet. On the third time, look to generalize the approach."

                                        1 Reply Last reply
                                        0
                                        • C chaiguy1337

                                          Frankly, I am getting tired of null reference exceptions. I just wish C#/.NET wouldn't be so finicky about null references. For example the latest issue I had was with a MediaPlayer object, where I close the (possibly) existing player before starting a new one: player.Stop(); player = new MediaPlayer(); ... But if I haven't already created a MediaPlayer I get a freaking null reference exception. Of course I know that I should know better and test player for null, but my point is I don't CARE if player.Stop() fails, it's not going to aversely affect my function at all anyway, and my argument is that I bet in 80-90% of cases, null reference exceptions that slip through in production code probably would work fine if they were simply ignored, like my example above. Who's with me for demanding that null reference exceptions be ignored by default and only thrown in blocks explicitly marked as such! Lol, just a mini-rant. :P

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

                                          S Offline
                                          S Offline
                                          Shog9 0
                                          wrote on last edited by
                                          #31

                                          logan1337 wrote:

                                          and my argument is that I bet in 80-90% of cases, null reference exceptions that slip through in production code probably would work fine if they were simply ignored, like my example above.

                                          Are you nuts? :~ You're responsible for telling the computer what to do. If you hand it a null reference, your method call can't actually be called. If you didn't need it to be called, you shouldn't have written it! Just think - you could have been trying to do anything. Essentially, you're saying that the runtime should plow through catastrophic bugs and attempt to keep executing something, on the assumption that major portions of your code aren't actually important anyway! No. No, no no. This is the road to unpredictable software, bugs that can never be reliably reproduced or tracked back to their original cause, shoddy software that works once, for the single scenario the developer tests under, but trashes the machines of half the end users. :sigh:

                                          ----

                                          ...the wind blows over it and it is gone, and its place remembers it no more...

                                          C 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