The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,878 other followers

.NET/C#: Class declarations initially set are indeed different than setting them in a constructor (via: Stack Overflow)

Posted by jpluimers on 2013/01/16

Thanks to Danny Thorpe and John Skeet, I learned something about C# initialization order.

I knew there were differences between declarations having their initial value set at the point of declaration, and inside a constructor, but not about all of them.

So I observed the initialization order while stepping through code, but the virtual method behaviour was new to me.

Thanks Blaz Art for asking this at SO.

Danny Thorpe:

For most purposes, you can consider the two styles of member initialization functionally equivalent.

However, you should keep in mind that assignments made in the member declarations execute before any constructors execute. As Jon Skeet points out in comments, this difference in timing can create observable artifacts if virtual methods are called from base constructors.

“Correctness” is a matter of opinion. For simple integer values the initial value assignments seem innocuous enough, but when you get into more complex types like dates or other full-on objects, the clutter factor starts to rise.

For myself, I generally prefer to see initialization performed as explicit assignment statements in the body of the constructor, not scattered all over the class in declarations.

John Skeet:

In general they’re not functionally equivalent – assignments made in the member declarations execute before the base class constructor too. If your base class constructor calls into some virtual method overridden in the derived class, it won’t see any initialization from the constructor body, but variable initializers will have been executed.

Danny Thorpe:

Good point, had forgotten about observability of the timing difference via virtual calls in constructors. Text updated.

–jeroen

via: c# – Are class declarations that are initially set, internally the same as setting them in the constructor? – tStack Overflow.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: