In my previous post on Constructors in C# 3.0 I stated that I didn’t understand the reasoning behind compilation creating two Employee objects in the way that it does.
Richard left the following comment.
I guess the second employee assignment is so the creation of the Employee seems atomic. If the assignment of FirstName threw an exception (for example), you’d never have a reference to the “incomplete” object.
I got to thinking that this didn’t make any sense. If you look at the disassembled code, an error on any of the property setter calls will throw an exception to the wrapping try/catch block, or, if one didn’t exist, the calling code (bad example in this case as there is no calling code, but you know what I’m getting at). If either happens the object being created will fall out of scope which means we wouldn’t be able to work with an “incomplete” object anyways.
What Richard did get me thinking about was possibility of creating a typing error during the setting of the properties at execution time. The first, and most obvious, attempt at creating a run time error was to assign an incorrect type in the constructor. As you can see below, that didn’t get me past compile time.
In addition to this, I attempted to assign the ID property a value from a variable defined using the var keyword and initialized to a string. Because the var keyword is implicitly typing the variable based on the value that it is initialized as, the same result was seen as the one that appears in the image above.
The only way that I was able to make this break at run time was to attempt to cast a string to an integer when it wasn’t possible. That isn’t the constructor failing though, it’s the Convert.ToInt32(obj) call causing the exception.
I think it’s fairly safe to say that it’s not possible to cause the property setters created by using the new constructor syntax to throw an exception. All exceptions that are possible would be typing based and those are handled at compile time.