I have some auto-instantiation code which I would like to apply to about 15 properties in a fairly big class. The code is similar to the following but the type is different for each instance:
protected ComplexType _propertyName;
public ComplexType PropertyName
{
get
{
if (_propertyName == null) {
_propertyName = new ComplexType();
}
return _propertyName;
}
}
To repeat this in C++ (as there are ~15 instances), I would have used a preprocessor macro but I notice C# doesn't support them.
I am wondering if anyone has a recommendation on how to do this cleanly in C#?
This might make things a bit neater, you could add this method to introduce some reuse:
protected ComplexType _propertyName;
public ComplexType PropertyName
{
get
{
return GetProperty(ref _propertyName);
}
}
.
.
private T GetProperty<T>(ref T property) where T : new()
{
if (property == null)
property = new T();
return property;
}
You can use the ??
operator to simplify the code into one line:
protected ComplexType _propertyName;
public ComplexType PropertyName
{
get
{
return _propertyName ?? (_propertyName = new ComplexType());
}
}
As a side note I would probably avoid protected fields. If you need to set the property from a derived class I would rather create a protected setter.
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