I have this:
AudioPlayer player = new AudioPlayer();
player.Directory = vc.Directory;
player.StartTime = vc.StarTime;
player.EndTime = vc.EndTime;
But I could have this:
AudioPlayer player = new AudioPlayer
{
Directory = vc.Directory,
StartTime = vc.StarTime,
EndTime = vc.EndTime
};
If I convert to ‘new way of writing things’, what do I gain besides unreadability? Will it make me closer to lambda functions ( => ) ?
Does it have something to do with RAII?
ADDITION:
Some answered that normal initialization could left the object in ‘invalid’ state after for example setting only a Directory property – my observation here is that is someone who was designing the object probably designed it in a way that only values that MUST be really entered are entered through real constructor, and all other could be freely modified later.
Consider you want to pass your newly created object to some method (and not do anything else with it). You can either write it the old way:
Or you can use object initializers:
Using object initilizers, you can clearly see what the code does and that the object is not used later.
Also, I think the readability (and “writability”) is better: you don’t have to repeat the variable name endlessly.