Awesome Try/Catch



  • Though an empty Catch is clearly not helpful, found this in a core library today that the team who owns the code was complaining that their process fails but they have no idea why.... (and I have no idea why they did it this way)

                    Catch ex As Exception
                        Dim s As String = ex.Message
                    End Try



  • I guess it could be usefull if you set a breakpoint to it in a debugger, but that is about it.



  • @dtech said:

    I guess it could be usefull if you set a breakpoint to it in a debugger, but that is about it.
     

    I do this all the time, but take out the code before checking it in.

    Sometimes it's ok to swallow the exception; but at least log it.



  • It takes care of the unused variable warning?  Although to complete that trick, I think you need s = s on the next line.



  • @frits said:

    It takes care of the unused variable warning?  Although to complete that trick, I think you need s = s on the next line.

    In a decent compiler, that would just trigger another warning for having an assignment statement without any effect...

     



  • @Anonymouse said:

    @frits said:

    It takes care of the unused variable warning?  Although to complete that trick, I think you need s = s on the next line.

    In a decent compiler, that would just trigger another warning for having an assignment statement without any effect...

     

    It probably does in Visual Studio,  but it doesn't matter for my throwaway joke.

     


  • Trolleybus Mechanic

    @frits said:

    It takes care of the unused variable warning?  Although to complete that trick, I think you need s = s on the next line.

     

    This works, too:

    @comeOnVB said:

        Try
            Dim seriouslyVB = 1 as Integer
            Dim sighVB = 0 as Integer
            Dim reallyVB = seriouslyVB / sighVB
        Catch

        End Try




  • I would also wrap that in a "if debug" directive so at least when you publish your rubbish, it gets removed and the exception gets bubbled up.



  • @C-Octothorpe said:

    I would also wrap that in a "if debug" directive so at least when you publish your rubbish, it gets removed and the exception gets bubbled up.

    Right.  What good's an exception, unless it only gets detected during production?



  • @frits said:

    @C-Octothorpe said:

    I would also wrap that in a "if debug" directive so at least when you publish your rubbish, it gets removed and the exception gets bubbled up.

    Right.  What good's an exception, unless it only gets detected during production?

    Silently swallowing your exceptions is a heaping pile of WTF to begin with.  Also, having it throw an exception in production is better than NEVER throwing one, no?

    I wasn't trying to say that this is the Right Way of doing it, but it's slightly less bad...  How about that?



  • I'm not sure I'd say that swallowing an exception in dev and throwing it in production is better than just swallowing it everywhere.  (Both are bad, though, of course)



  • @Sutherlands said:

    I'm not sure I'd say that swallowing an exception in dev and throwing it in production is better than just swallowing it everywhere.  (Both are bad, though, of course)

    Bullshit.  You're honestly telling me you would rather have no exception at all?  Again, I'm not saying either situation is good, but having an exception is better than none at all.

    At least in this case you would have the stack trace to go through the code and find where it's coming from (and also remove the swallowing exception logic).



  • @C-Octothorpe said:

    @Sutherlands said:

    I'm not sure I'd say that swallowing an exception in dev and throwing it in production is better than just swallowing it everywhere.  (Both are bad, though, of course)

    Bullshit.  You're honestly telling me you would rather have no exception at all?  Again, I'm not saying either situation is good, but having an exception is better than none at all.

     

    The choice you were presenting isn't exception vs. no exception, you were saying exception vs. prod not matching what you did your testing on (dev stuff).



  • My bad; that's not what I was trying to say.  I blame my ADD...

    On another note, this would be an interesting (yet obvious) way of "accidentally" introducing interesting bugs into production which don't show up in dev.  Wait, wow, what I said before IS much worse than no exceptions at all...



  • @C-Octothorpe said:

    Silently swallowing your exceptions is a heaping pile of WTF to begin with.
     

     

    I've legitimately done it in at least two situations (pro-active cleanup of some temp files, and some "remote host closed connection" conditions that ASP.NET considers to be errors).

     



  • @emurphy said:

    some "remote host closed connection" conditions that ASP.NET considers to be errors

    Exceptions != errors.



  • Meh, you can still argue that they should at least be logged somewhere even as informational in the event something unexpected starts happening.  You should program defensively, in that (ideally) there shouldn't ever be exceptions.  Exceptions are just that, they're exceptional (circumstances).  If you're expecting something to fail, it's no longer exceptional.

    Now there are cases where stuff happens outside of your control (i.e. .Net throwing unavoidable exceptions like your example and my personal pet peeve is trying to access Session when it's not available without it throwing an exception), and I would say swallow it here, but still log it.  Or at the very least swallow the certain exception with a certain message that you're looking for and log/throw anything else.



  • @C-Octothorpe said:

    Wait, wow, what I said before IS much worse than no exceptions at all...

    BS, you're honestly saying that throwing exceptions all the time is better than writing a program that works?  Oh wait, that's not what I was trying to say. :P


  • I have code like this in my source all over the place:

    
    int woodchucks = DEFAULT_WOODCHUCK_COUNT;
    try {
        woodchucks = Integer.parseInt(sketchyUserInput);
    } catch (NumberFormatException dontCare) {}
    

    It's not so bad to swallow unwanted exceptions, is it? It all depends on context, on what actually is exceptional and what is merely a subclass of Exception. It's during these reflections that I pine for the simple solution: multivalue returns, in this case one for parse success, the other for the int value. Oh well, maybe in the next popular language.


  • Garbage Person

    @Xyro said:

    I have code like this in my source all over the place:

     

    
    int woodchucks = DEFAULT_WOODCHUCK_COUNT;
    try {
        woodchucks = Integer.parseInt(sketchyUserInput);
    } catch (NumberFormatException dontCare) {}
    
    Note that this results in a warning about an unused variable called dontCare. You actually want to just catch(NumberFormatException) (without naming it)


  •  

    It's during these reflections that I pine for the simple solution: multivalue returns, in this case one for parse success, the other for the int value. Oh well, maybe in the next popular language. 


    Wouldn't that be int.TryParse? I mean, it obviously doesn't return a tuple (which I might add are in the latest version of C#, I think), but it has the functionality you are looking for to avoid catching a NumberFormatException.

     

    returns true if it succeeds, false otherwise, takes the number to parse and  an out parameter. So your exception block becomes:


    int woodchucks=DEFAULT_WOODCHUCK_COUNT;


    int.TryParse(sketchyUserInput,out woodchucks);


  • Garbage Person

    @BC_Programmer said:


    Wouldn't that be int.TryParse? I mean, it obviously doesn't return a tuple (which I might add are in the latest version of C#, I think), but it has the functionality you are looking for to avoid catching a NumberFormatException.

     

    returns true if it succeeds, false otherwise, takes the number to parse and  an out parameter. So your exception block becomes:


    int woodchucks=DEFAULT_WOODCHUCK_COUNT;


    int.TryParse(sketchyUserInput,out woodchucks);

    Personally, I don't like TryParse. Output parameters are harder to follow on a quick read.


    int woodchucks
    try {
    woodchucks = Integer.parseInt(sketchyUserInput);
    }
    catch (NumberFormatException)
    {
    woodchucks = DEFAULT_WOODCHUCK_COUNT;
    }
     

    is probably better (unless this causes warnings about woodchucks being uninitialized, in which case Microsoft needs a beating.)

     



  • Well, sure, if you want to be throwing and catching exceptions the whole time in your code. 

     

    Btw, I think the "correct" version would be:

    if(!int.TryParse(userInput, out varName))

       varName = DEFAULT_VALUE;

     

    Edit: And by "correct" I mean correct, since setting the variable before the out would do absolutely nothing, since the function is required to assign a value to it before it exits.



  • @Sutherlands said:


    Btw, I think the "correct" version would be:

    if(!int.TryParse(userInput, out varName))

       varName = DEFAULT_VALUE;

    Thanks, I had a feeling there was something off about my example, I was thinking of the second parameter semantically as a ref (and assuming TryParse left the parameter as is in the case of failure) but as you note out parameters <must> be assigned to so obviously any value given to it previously will be lost.

     

     



     



  • Psh, .Net? I'm using Java. We don't need no unnamed exception catches or sticking out parameters. ... Okay, so maybe we do. And all the other features you guys have. Sigh.



  • @Xyro said:

    I have code like this in my source all over the place:

    
    int woodchucks = DEFAULT_WOODCHUCK_COUNT;
    try {
        woodchucks = Integer.parseInt(sketchyUserInput);
    } catch (NumberFormatException dontCare) {}
    

     

    It's not so bad to swallow unwanted exceptions, is it? It all depends on context, on what actually is exceptional and what is merely a subclass of Exception. It's during these reflections that I pine for the simple solution: multivalue returns, in this case one for parse success, the other for the int value. Oh well, maybe in the next popular language.

    Obvious troll is obvious...



  • General comment on exceptions...I work on some extreme reliability systems. It is not uncommon to have the act of throwing an exception (even if it is caught) to trigger a "CritSit" if the exact scenario (i.e. context, stack trace, etc.) is not already on-file as a known operational condition. This CritSit can trigger a persons pager (or modern equivilant) going off in the middle of the night to examine the cause and approve continued use of the system.

     For cleaner .NET code:<FONT size=2 face=Consolas><FONT size=2 face=Consolas></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>

    </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>static</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>class</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas>Helpers
    </FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>{
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>public</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>static</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>int</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> ? TryParseInt(</FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>this</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>string</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> source)
       {
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>int</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> value;
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>if</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> (</FONT></FONT><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas>Int32</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>.TryParse(source, </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>out</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> value))
          </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>return</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> value;
         </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>else
          </FONT></FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>return</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>null</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>;
       }
    }</FONT></FONT>

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas>Allows:</FONT></FONT>

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas><FONT size=2 face=Consolas><FONT size=2 face=Consolas>

    </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>   string</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> a = </FONT></FONT><FONT color=#a31515 size=2 face=Consolas><FONT color=#a31515 size=2 face=Consolas><FONT color=#a31515 size=2 face=Consolas>"1"</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>;
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>int</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>? value = a.TryParseInt();</FONT></FONT>

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas></FONT></FONT> 

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas> 

    </FONT></FONT></FONT></FONT>


  • That does seem cleaner, but then rather than checking for true/false, you're now checking for null which could be worse as this could give a false sense of security.  I'm guessing this is a popular usage pattern with this extension?

    var intValue = "this is not an integer".TryParseInt().Value;



  • Well, given the fact that it's not anyone I personally know that uses it... I would have to say that likely anyone who is good enough to clean up their code in that way is also good enough to not use the .Value at the end.


  • Garbage Person

    @TheCPUWizard said:

    <font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">static</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">class</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font><font color="#2b91af" face="Consolas" size="2"><font color="#2b91af" face="Consolas" size="2"><font color="#2b91af" face="Consolas" size="2">Helpers
    </font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2">{
       </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">public</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">static</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">int</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> ? TryParseInt(</font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">this</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">string</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> source)
       {
       </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">int</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> value;
       </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">if</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> (</font></font><font color="#2b91af" face="Consolas" size="2"><font color="#2b91af" face="Consolas" size="2"><font color="#2b91af" face="Consolas" size="2">Int32</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2">.TryParse(source, </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">out</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> value))
          </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">return</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> value;
         </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">else
          </font></font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">return</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">null</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2">;
       }
    }</font></font>

    <font face="Consolas" size="2"><font face="Consolas" size="2">Allows:</font></font>

    <font face="Consolas" size="2"><font face="Consolas" size="2"><font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font>

    <font face="Consolas" size="2"><font face="Consolas" size="2"></font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">   string</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2"> a = </font></font><font color="#a31515" face="Consolas" size="2"><font color="#a31515" face="Consolas" size="2"><font color="#a31515" face="Consolas" size="2">"1"</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2">;
       </font></font><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2"><font color="#0000ff" face="Consolas" size="2">int</font></font></font><font face="Consolas" size="2"><font face="Consolas" size="2">? value = a.TryParseInt();</font></font>

    <font face="Consolas" size="2"><font face="Consolas" size="2"></font></font> 

    <font face="Consolas" size="2"><font face="Consolas" size="2"> </font></font>

    </font></font>
    Today I learned: That Extension Methods exist.

     

    Of course, working with nullable primitives is annoying as hell, too, because nothing in the entire framework takes them as parameters. For the specific woodchucks-parameter-example, I'd pass in the default to the extension method and have it return that instead of a null.



  • @Weng said:

    @TheCPUWizard said:

    <FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>static</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>class</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas>Helpers
    </FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>{
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>public</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>static</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>int</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> ? TryParseInt(</FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>this</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>string</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> source)
       {
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>int</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> value;
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>if</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> (</FONT></FONT><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas><FONT color=#2b91af size=2 face=Consolas>Int32</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>.TryParse(source, </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>out</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> value))
          </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>return</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> value;
         </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>else
          </FONT></FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>return</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>null</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>;
       }
    }</FONT></FONT>

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas>Allows:</FONT></FONT>

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas><FONT size=2 face=Consolas><FONT size=2 face=Consolas></FONT></FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas></FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>   string</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas> a = </FONT></FONT><FONT color=#a31515 size=2 face=Consolas><FONT color=#a31515 size=2 face=Consolas><FONT color=#a31515 size=2 face=Consolas>"1"</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>;
       </FONT></FONT><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas><FONT color=#0000ff size=2 face=Consolas>int</FONT></FONT></FONT><FONT size=2 face=Consolas><FONT size=2 face=Consolas>? value = a.TryParseInt();</FONT></FONT>

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas></FONT></FONT> 

    <FONT size=2 face=Consolas><FONT size=2 face=Consolas></FONT></FONT> 

    </FONT></FONT>
    Today I learned: That Extension Methods exist.

     

     

    Of course, working with nullable primitives is annoying as hell, too, because nothing in the entire framework takes them as parameters. For the specific woodchucks-parameter-example, I'd pass in the default to the extension method and have it return that instead of a null.

    Assuming you're not trolling:

    No, it's ok as is.  Check out Nullable<T>.GetValueOrDefault (it's overloaded).  This should do just fine.

    He can also get all generic and pass in a Func<T, bool> where the func would be the <T>.TryParse method.  This way it doesn't tie to you just int (or creating overloads for each type).

    I would also like to point out that this is all an exercise in futility as we're just reinventing the wheel without making it a whole lot rounder.



  • @Weng said:

    Today I learned: That Extension Methods exist.

    Read Effective C# and More Effective C#.  TheCPUWizard will say there's some stuff in there that's outdated, although he hasn't specifically told me what, but they're awesome books.

    @Weng said:

    Of course, working with nullable primitives is annoying as hell, too, because nothing in the entire framework takes them as parameters. For the specific woodchucks-parameter-example, I'd pass in the default to the extension method and have it return that instead of a null.

     public static int TryParseInt(this string source, int default)

    {

       int value;

       if(!int.TryParse(source, out value))

          value = default;

       return value;

    }

    if(string.Empty.TryParseInt(DEFAULT_VALUE) == DEFAULT_VALUE)

       throw new Exception();

    if(DEFAULT_VALUE.ToString().TryParseInt(DEFAULT_VALUE) == DEFAULT_VALUE)

       throw new Exception();

     

    If you're not using nullables, you no longer have the information on whether it was a valid number, that information has been lost.  If you don't care, it's fine; but for an extension function it's better to make it reusable.



  • @C-Octothorpe said:

    He can also get all generic and pass in a Func<T, bool> where the func would be the <T>.TryParse method.  This way it doesn't tie to you just int (or creating overloads for each type).

    Well, because of the out parameter, the best you could do is declare it as Func<T, out T, bool> - and I'm not sure whether or not you can declare out params in generic signatures (although I don't see why not).  Better to just keep it as the original (or just use the TryParse in your code directly, it's not that hard).



  • Actually, having a second look at it it would likely be Func<string, out T, bool>, and the extension method return type would be T? with maybe a generic constraint of struct of something.

    And as I stated in my last post, this is mostly adding "style" and isn't really making the code cleaner or more tearse, IMO.



  • Some really good comments. My responses.

    • Scott's books are great, but they are "outdated" in the sense that they do not take into account changes that are part of the newer releases of the .NET framework.
    • Func<out T> - You cant do that. Func<...> (and Action<...>) are some predefined delegates, if you want ref or out parameters you have to create your own delegates...from there on your are ok...except...
    • out parameters are not "friendly" will LINQ and expression trees (or other places where there can be multiple closures.
    • <font size="2" face="Consolas"><font size="2" face="Consolas">You really can not make the extension methods generic as there is no common interface for the "TryParse"</font></font>


  • Not making the code cleaner????

     var seq = new List<string> { "1""2""3""not a number""four" };

    <font size="3" face="Times New Roman">

      </font>var nums = from item in seq
    select item.TryParseInt() ?? 0;

    <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p> Does anyone else want to post a more concise and readable solution that will result in</o:p>

    <o:p> [ 1,2,3,0,0 ]</o:p><o:p> </o:p>

    <font size="3" face="Times New Roman">

    </font> 



  • @TheCPUWizard said:

    Not making the code cleaner????

     var seq = new List<string> { "1""2""3""not a number""four" };

    <FONT size=3 face="Times New Roman">  </FONT>var nums = from item in seq select item.TryParseInt() ?? 0;

     Does anyone else want to post a more concise and readable solution that will result in

     [ 1,2,3,0,0 ] 

    var nums = new []] {1, 2, 3, 0, 0}

    :)


  • Trolleybus Mechanic

    @TheCPUWizard said:

    Not making the code cleaner????

     var seq = new List<string> { "1""2""3""not a number""four" };

    <font face="Times New Roman" size="3">

      </font>var nums = from item in seq
    select item.TryParseInt() ?? 0;

     Does anyone else want to post a more concise and readable solution that will result in

     [ 1,2,3,0,0 ] 

     

    Response.Write("[ " & API.TheDailyWTF.GetMsg(255288).Text().Split("[")(1).Split("]")  & " ]")



  • @Lorne Kates said:

    Response.Write("[ " & API.TheDailyWTF.GetMsg(255288).Text().Split("[")(1).Split("]")  & " ]")

    Took me a few seconds to "Get it"...then I fell out of my chair!!!!

    It is more verbose [94 vs. 60] characters - but I dont think that should EVER be a deciding factor.  Definately a prize for cleverness, but "clever" programmers typically cost a company more....


  • Garbage Person

    @Sutherlands said:

    Read Effective C# and More Effective C#.  TheCPUWizard will say there's some stuff in there that's outdated, although he hasn't specifically told me what, but they're awesome books.
    Oddly enough, they're actually on the shelf. I just haven't gotten to them yet.



  • Bah, where's my prize for simplicity?!


  • Trolleybus Mechanic

    @Sutherlands said:

    Bah, where's my prize for simplicity?!

     

    I put a biscuit in the chute that made the dog run across the treadmill so the recoiling arms would open the shipping box which would cause a draft that ignites a ember into a flame that burns the rope that tips the bucket that dumps that packing popcorn into the box which weights it down that activates a pressure switch that spins the fan that blows the sailboat onto the see saw that tips that balance so your trophy will roll down the spiral chute into the box that tips a second seesaw that runs it under a hamster wheel with backwards packing tape and finally ends up in the UPS out box.

    I don't know why you haven't got it in the mail yet.



  • Extremenly simple, but it may violate Einsteins principle: "Make things as simple as possible...but no simpler.."



  • @Lorne Kates said:

    @Sutherlands said:

    Bah, where's my prize for simplicity?!

     

    I put a biscuit in the chute that made the dog run across the treadmill so the recoiling arms would open the shipping box which would cause a draft that ignites a ember into a flame that burns the rope that tips the bucket that dumps that packing popcorn into the box which weights it down that activates a pressure switch that spins the fan that blows the sailboat onto the see saw that tips that balance so your trophy will roll down the spiral chute into the box that tips a second seesaw that runs it under a hamster wheel with backwards packing tape and finally ends up in the UPS out box.

    I don't know why you haven't got it in the mail yet.

    Someone has been playing too much The Incredible Machine


  • @Lorne - post the video!!!!!


  • Trolleybus Mechanic

    @TheCPUWizard said:

    @Lorne - post the video!!!!!
     

    I tried to, but YouTube is way to complicated. =(


Log in to reply