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. Other Discussions
  3. IT & Infrastructure
  4. Using TryXXX pattern ?

Using TryXXX pattern ?

Scheduled Pinned Locked Moved IT & Infrastructure
csharpdotnetregextutorialquestion
7 Posts 6 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.
  • B Offline
    B Offline
    beatles1692
    wrote on last edited by
    #1

    Hi Since .net framework 2 there are some methods that using a pattern like this: bool TrySomething(args1,2,...,out result) For example int.TryParse which accepts a string and if it's true it will return its int value using an out argument. I don't know if it's a good programming practice or not. What do you think?

    G L 2 Replies Last reply
    0
    • B beatles1692

      Hi Since .net framework 2 there are some methods that using a pattern like this: bool TrySomething(args1,2,...,out result) For example int.TryParse which accepts a string and if it's true it will return its int value using an out argument. I don't know if it's a good programming practice or not. What do you think?

      G Offline
      G Offline
      Giorgi Dalakishvili
      wrote on last edited by
      #2

      TryXXX methods returns true if it succeeds and false if it fails. The advantage is that it doesn't throw exception if it fails opposed to XXX method so your code will look cleaner and might event run faster as there is no need to throw and catch an exception.

      Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

      R 1 Reply Last reply
      0
      • B beatles1692

        Hi Since .net framework 2 there are some methods that using a pattern like this: bool TrySomething(args1,2,...,out result) For example int.TryParse which accepts a string and if it's true it will return its int value using an out argument. I don't know if it's a good programming practice or not. What do you think?

        L Offline
        L Offline
        led mike
        wrote on last edited by
        #3

        beatles1692 wrote:

        I don't know if it's a good programming practice or not.

        Exceptions are aptly named and Best Practice can, to a degree, be understood from the name alone. Exceptional conditions are what Exceptions are best suited for. If the conditions are expected then they are not exceptional, therefore Exceptions are not suited to handling the condition. This is where the TryXXX methods are better suited. Does that help?

        led mike

        M 1 Reply Last reply
        0
        • G Giorgi Dalakishvili

          TryXXX methods returns true if it succeeds and false if it fails. The advantage is that it doesn't throw exception if it fails opposed to XXX method so your code will look cleaner and might event run faster as there is no need to throw and catch an exception.

          Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

          R Offline
          R Offline
          Ray Cassick
          wrote on last edited by
          #4

          Not sure if this is really a performance issue or not since I think these methods still catch an exception internally, they just don't expose it to the caller. Might be an interesting test to run...


          FFRF[^]
          My LinkedIn profile[^]
          My Programmers Blog[^]

          S 1 Reply Last reply
          0
          • L led mike

            beatles1692 wrote:

            I don't know if it's a good programming practice or not.

            Exceptions are aptly named and Best Practice can, to a degree, be understood from the name alone. Exceptional conditions are what Exceptions are best suited for. If the conditions are expected then they are not exceptional, therefore Exceptions are not suited to handling the condition. This is where the TryXXX methods are better suited. Does that help?

            led mike

            M Offline
            M Offline
            Mark Churchill
            wrote on last edited by
            #5

            Correct. Also people should get in the habit of developing with exceptions set to "Break on thrown", not just "Break on unhandled". The TryXXX functions help this because you don't get (fairly) expected errors - and even though they just wrap a try/catch internally, they hide it from your code. Using an SVG library at the moment that doesnt expose TryGet or Contains, so you just have to use try...get...catch, its ugly, and makes me break into the debugger every damn time :(

            Mark Churchill Director, Dunn & Churchill Pty Ltd Free Download: Diamond Binding: The simple, powerful, reliable, and effective data layer toolkit for Visual Studio.
            Alpha release: Entanglar: Transparant multiplayer framework for .Net games.

            L 1 Reply Last reply
            0
            • M Mark Churchill

              Correct. Also people should get in the habit of developing with exceptions set to "Break on thrown", not just "Break on unhandled". The TryXXX functions help this because you don't get (fairly) expected errors - and even though they just wrap a try/catch internally, they hide it from your code. Using an SVG library at the moment that doesnt expose TryGet or Contains, so you just have to use try...get...catch, its ugly, and makes me break into the debugger every damn time :(

              Mark Churchill Director, Dunn & Churchill Pty Ltd Free Download: Diamond Binding: The simple, powerful, reliable, and effective data layer toolkit for Visual Studio.
              Alpha release: Entanglar: Transparant multiplayer framework for .Net games.

              L Offline
              L Offline
              led mike
              wrote on last edited by
              #6

              Mark Churchill wrote:

              Also people should get in the habit of developing with exceptions set to "Break on thrown"

              Nice tip, thanks! :)

              led mike

              1 Reply Last reply
              0
              • R Ray Cassick

                Not sure if this is really a performance issue or not since I think these methods still catch an exception internally, they just don't expose it to the caller. Might be an interesting test to run...


                FFRF[^]
                My LinkedIn profile[^]
                My Programmers Blog[^]

                S Offline
                S Offline
                Simon P Stevens
                wrote on last edited by
                #7

                Ray Cassick wrote:

                I think these methods still catch an exception internally, they just don't expose it to the caller.

                I used to think this, but it's quite the opposite actually. Take a look at the Int.TryParse(x) methods in reflector. They both call the same underlying methods (NumberToInt33 and HexNumberToInt32 depending on the string format), which return booleans, and then the difference is that the TryParse methods return true/false based on the result, where as the Parse method actually throws an exception based on the boolean result.

                internal static unsafe uint ParseUInt32(string value, NumberStyles options, NumberFormatInfo numfmt)
                {
                byte* stackBuffer = stackalloc byte[1 * 0x72];
                NumberBuffer number = new NumberBuffer(stackBuffer);
                uint num = 0;
                StringToNumber(value, options, ref number, numfmt, false);
                if ((options & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
                {
                if (!HexNumberToUInt32(ref number, ref num))
                {
                throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
                }
                return num;
                }
                if (!NumberToUInt32(ref number, ref num))
                {
                throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
                }
                return num;
                }

                internal static unsafe bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)
                {
                byte* stackBuffer = stackalloc byte[1 * 0x72];
                NumberBuffer number = new NumberBuffer(stackBuffer);
                result = 0;
                if (!TryStringToNumber(s, style, ref number, info, false))
                {
                return false;
                }
                if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
                {
                if (!HexNumberToInt32(ref number, ref result))
                {
                return false;
                }
                }
                else if (!NumberToInt32(ref number, ref result))
                {
                return false;
                }
                return true;
                }

                (There are other differences, like one calls TryStringToNumber, but if you follow the stack all the way down, the Try method doesn't ever suppress an exception) I don't know if this is true for all TryXXX methods, but it's the same for the ones I've looked at.

                Simon

                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