Given the following example, is one objectively better/faster/safer than the other? Should object literal instantiation be a best practice where it is practical?
Where is this inappropriate?
class Person
{
public string name;
public int age;
}
void MakePeople()
{
Person myPerson = new Person();
myPerson.name = "Steve";
myPerson.age = 21;
Person literalPerson = new Person { name = "John", age = 22 };
}
No, it isn't faster or slower. It is the same.
The compiler translates object initializers to a constructor call followed by setting those properties.
Person literalPerson = new Person { name = "John", age = 22 };
Turns to:
Person myPerson = new Person();
myPerson.name = "John";
myPerson.age = 22;
You should use what is more readable and what you have agreed on with your team.
Either is appropriate. It depends on what you need to do to set properties. For example, I would avoid literal instantiation in cases where some logic is needed to arrive at a property value:
Person myPerson = new Person();
myPerson.SomeProperty = if IsNewPerson ? GetPropertyFromDatabase() : GetDefaultProperty();
Edit:
One advantage to using literal object initialization in Visual Studio is that Intellisense will prompt for properties, showing only those which have not already been declared. (I've ran into code where a value was redundantly assigned when setting properties.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With