Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 248
Ryall Avatar asked Sep 07 '09 09:09

Ryall


2 Answers

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;
}
like image 110
Charlie Avatar answered Oct 21 '22 20:10

Charlie


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.

like image 30
Martin Liversage Avatar answered Oct 21 '22 20:10

Martin Liversage