When setting up some reference type properties for a project I'm working on, I came accross a few properties that needed to be properly initialized to be used and should never be null. I've seen a few ways to handle this and can't really determine if there are any major drawbacks to any of the primary ways I've seen to handle this. I'd like to get the community's opinion about the best way to handle this and what the potential drawbacks to each method might be.
Given a simple class, I've seen several ways to handle making sure a property never has a null version of this class in a property
public class MyClass
{
//Some collection of code
}
Option 1 - Initialize the backing store
public class OtherClass1
{
private MyClass _mC = new MyClass();
public MyClass MC
{
get { return _mC; }
set { _mC = value; }
}
}
Option 2 - Initialize the property in the constructor
public class OtherClass2
{
public MyClass MC { get; set; }
public OtherClass2()
{
MC = new MyClass();
}
}
Option 3 - Handle initialization as needed in the Getter
public class OtherClass3
{
private MyClass _mC;
public MyClass MC
{
get
{
if (_mC == null)
_mC = new MyClass();
return _mC;
}
set { _mC = value; }
}
}
I'm sure there are other ways, but these are the ones that come to mind and I have seen. I'm mostly trying to determine if there's a well established best practice on this or if there's a specific concern with any of the above.
Cheers,
Steve