What is the behavior when throwing an exception without setting out parameter?

What is the defined behaviour in C# for when an exception is thrown before setting the value of an out parameter, and you then try to access the parameter?

public void DoSomething(int id, out control)
{
    try
    {
        int results = Call(Id);
        control = new CallControl(results);
    }
    catch(Exception e)
    {
      throw new Exception("Call failed", e);
    }
}

//somewhere else
DoSomething(out Control control)
{
    try
    {
       DoSomething(1, out control);
    }
    catch()
    {
    // handle exception
    }
}

// later
Control control;
DoSomething(out control)
control.Show();

The compiler normally complains about exiting the method before setting the out parameter. This seems to outsmart it from protecting me from myself.

Jon Skeet
people
quotationmark

What is the defined behaviour in C# for when an exception is thrown before setting the value of an out parameter, and you then try to access the parameter?

You can't do so. The variable will still not be definitely assigned, unless it's definitely assigned before the method call.

If the variable was definitely assigned before the method call, then it will still be definitely assigned - but unless the method assigned a value before the exception was thrown, the variable's value will remain untouched:

class Test
{
    static void JustThrow(out int x)
    {
        throw new Exception();
    }

    static void Main()
    {
        int y = 10;
        try
        {
            JustThrow(out y);
        }
        catch
        {
            // Ignore
        }
        Console.WriteLine(y); // Still prints 10
    }
}

people

See more on this question at Stackoverflow