Alex Rivera | Logout

Setting properties via object initialization or not: Any difference?

Asked 2011-02-11T20:01:44.227
38

Is there any (performance) difference between this:

Person person = new Person()
{
  Name = "Philippe",
  Mail = "phil@phil.com",
};

and this:

Person person = new Person();
person.Name = "Philippe";
person.Mail = "phil@phil.com";

You can imagine a bigger object with more properties.

Edit
Report

1 Answer

10

One additional thing worth noting is this:

If you fail to handle an exception in your constructor, you'll get a TypeInitializationException. While that may not seem so bad, the truth is that it conceals the real cause of the problem, and makes it harder to track down.

If, on the other hand, you use an object initializer, you're invoking each property individually outside of the constructor, and any thrown exceptions will be very clear and very evident: they won't be masked by the TypeInitializationException.

In general, it's a bad idea to throw exceptions in a constructor. If you want to avoid that scenario, go with the initializer.

answered 2011-02-11T21:13:16.950

Your Answer