Edit: Though I’ve accepted David’s answer, Jon’s answer should be considered as well.
Which method is preferred for setting the value of a read only (get only?) Property: using a backing field or using the constructor? Assume the design is for a Property and not a Field (in the future, there may be an update that requires the Property to have a setter which would preclude using a Field).
Given the following simple example, which method is preferred? If one is preferred over the other, why?
Option 1 (backing field):
class SomeObject
{
// logic
}
class Foo
{
private SomeObject _myObject;
public SomeObject MyObject
{
get
{
if( _myObject == null )
{
_myObject = new SomeObject();
}
return _myObject;
}
}
public Foo()
{
// logic
}
}
Option 2 (constructor):
class SomeObject
{
// logic
}
class Foo
{
public SomeObject MyObject { get; private set; }
public Foo()
{
MyObject = new SomeObject();
// logic
}
}
It depends on the time needed by “new SomeObject();” and the likelihood that the getter is going to be called at all.
If it’s costly to create MyObject, and won’t be used every time you create an instance of Foo(), option 1 is a good idea, and that’s called lazy initialization. Programs like Google Chrome use it heavily to reduce startup time.
If you’re going to create MyObject every time anyways, and the getter is called very often, you’ll save a comparison on each access with option 2.