Search code examples
c#out

How to tell if an out parameter was set already?


Is there a way to know if an out parameter was set already or not. This is the pseudocode for what I am looking for:

public virtual string blabla(long num, out bool bval)
    {
        if (!bval.HasValue)
            {
            //Do some default logic
            bval = defaultValue;
            }

        return blabla2(num, bval);
    }

Solution

  • You can't - you can't read the variable until it's been definitely assigned within your method. You should think of it as being like a local variable, declared but not assigned any value at the start of the method - but which you must assign a value to before you return. (It's okay not to have assigned a value to it if an exception is thrown.)

    If you want a parameter which carries information as input to the method as well as propagating information out, you should use ref instead of out.

    See my article on parameter passing for more information.