Hawaiʻi's Technology and New Media Community

I'm just starting to play with some of the new features in .NET, especially LINQ and the language features that were added to support it. I was wondering what other people think about object intializers. They seem quite handy but I'm concerned that encapsulation may suffer...

Views: 28

Reply to This

Replies to This Discussion

How do they violate encapsulation? I really like object initializers. They exist in other languages like Python and Groovy.

new Student { Name="Tim" };

new Student(name:"Tim");
They don't, per se, but you must be careful that your default constructor behaves in a manner that object initializers will not compromise. Part of the reason for overloaded constructors is to allow an object to be initialized differently with different input scenarios. A ctor like Foo() may initialize differently than Foo(bar). Under the object initializers, you must ensure that new Foo() { prop=bar } initializes the same as

Foo foo = new Foo();

In other words, the object has to be initialized to the same state regardless of the constructor.

I'm not necessarily down on the concept; I just believe that it requires a little more diligence on the programmer's behalf.

Reply to Discussion



web design, web development, localization

© 2015   Created by Daniel Leuck.   Powered by

Badges  |  Report an Issue  |  Terms of Service