C# Equivalent for C++ Macros and using Auto<> Properties

c#, coding-style, properties

Solution

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;
}

Problem

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#?

Original source