Are there issues with returning a new instance from an accessor? If so, is there a better approach?
public class Person
{
private RecIpDet _ipDet;
public RecIpDet IpDet
{
get
{
if(_ipDet == null)
_ipDet = new RecIpDet();
return _ipDet;
}
}
}
There are issues, because you never set your field, so you’ll return a new object everytime the property is called.
You should set
_ipDetif it’s null, and then return it. This is called lazy instantiation or lazy initialization.Keep in mind, this is not thread-safe, so if that’s a factor for you, you’ll need a more robust mechanism. For single threaded applications, this method of lazy instantiation is fine.
If you’re using .NET 4.0 or higher, you can use the
Lazy<T>class, which I believe is thread-safe: