Thoughts on object initialisers?

One of my favourite features on C# is the ability to do:

var someObject = new AnObject { SomeProperty = 5, AnotherProperty = true }; 

I'm working on a project at the minute that makes gratuitous use of this pattern, but I'm concerned that in some cases, the initialiser is too complex. Is my concern merited?

Here's one as an example, with the variable names substituted:

var something = new Something { PropA = e.Foo, PropB = e.Bar, PropC = ParseSomething(e.FooBar), Id = e.Id, PropD = (uint)e.Blah, Selected = e.Selected, Deleted = e.Deleted, SomeData = e.SomeValues == null ? null : e.InputValues.Select(d => new AnotherObject { ID = d.Id, Values = d.Something.Select(c => new SomeKeyValuePairObject { Key = c.Foo, Value = c.Bar }).ToList() }).ToList() }; 

Other than the fact that this can be a nightmare to debug (which is what caused me to post this question), are there any other reasons to avoid doing the above?

by BirdFluLol via /r/csharp

Leave a Reply