Throw new exception using object initializer

Let's consider this code :

try
{
    return new ClassA.GetStuff();
}
catch (Exception e)
{
    throw new MyException
        ("message", e)
        {SomeMyExceptionProperty = "something"};
}

When throwing MyException, how the object initialization is done? Like this :

MyException myException = new MyException("message", e);
myException.SomeMyExceptionProperty = "something";
throw myException;

or like this (so the SomeMyExceptionProperty is not initialized) :

MyException myException = new MyException("message", e);
throw myException;
myException.SomeMyExceptionProperty = "something"; //unreachable code

I think that the first behavior is used, like for a return statement, but where is the official documentation about this?

Jon Skeet
people
quotationmark

As ever, the official documentation is the C# specification.

The important part is that this is just a throw statement. It has two parts (in this case):

  • The keyword throw
  • An expression which determines the exception to throw

In this case, the expression includes an object initializer. The whole expression is evaluated before anything is thrown.

From section 8.9.5 of the C# 5 spec:

A throw statement with an expression throws the value produced by evaluating the expression.

Evaluating the expression

new MyException
    ("message", e)
    {SomeMyExceptionProperty = "something"}

... includes assigning the value "something" to the SomeMyExceptionProperty.

people

See more on this question at Stackoverflow