[Solved] Why doesn’t my C# compiler (Visual Studio) let me do this with a try block?


I’ll go over your points one by one:

  1. Declare long presult; right before the try statement. This makes the
    compiler mad because it wrongly thinks there’s a possibility of
    returning an unintialized variable.

Actually, the compiler correctly determines that there is the possibility of returning an uninitialized variable. Since the variable is only set if the function on the right hand side succeeds, and since you have it in a try..catch block then there is the possibility that the function may throw and not return, therefore not initializing the variable. What the compiler is not smart enough to see is that you are catching the top level exception and throwing (in a bad way, losing the stack trace) and it should not reach the return. However there are ways to get around that (mostly during debug by dragging the execution cursor).

  1. Initialize it with long presult = default(long). This works, but
    it’s bad practice because someone reading the code doesn’t know
    whether intializing it to the default value is to work around the
    problem described in 1. or is because the value presult because set
    to the default long has some real meaning in the context of the
    program.

Since value types like long, int, short etc must have a value, this is not bad practice. If you want to represent them as not having a value, use the nullable versions of those types (i.e. long? presult = null).

  1. Initialize it with long? presult = null. This is semantically better
    because it’s clear that it means “presult is meant to have no value
    at this point” whereas in 2. the reader has to figure out that
    presult has a meaningless value. The problem here is that, not only
    does it take extra memory to nullify a value, but I then have to
    change the function EvalInner to return a long? and this results in
    a chain of needing to change many more longs to long?s and my
    program ends up splattered with nullified variables; it’s a complete
    mess of question marks haha.

Again, the function must return a value that is a valid long, so if you want to return something that can easily be identified as an incorrect value, then return the nullable version, otherwise you have to return a valid value. Only float and double have NaN members…

Another option would be some kind of TryXXX method, where the return value is a boolean and you use an out long as a parameter to store the result.

solved Why doesn’t my C# compiler (Visual Studio) let me do this with a try block?