DaveDev DaveDev - 1 month ago 9
C# Question

Test if a Property is not Null before Returning

I have the following property

public MyType MyProperty {get;set;}


I want to change this property so that if the value is null, it'll populate the value first, and then return it... but without using a private member variable.

For instance, if I was doing this:

public MyType MyProperty
{
get
{
if (_myProperty != null)
return _myProperty
else
_myProperty = XYZ;
return _myProperty;
}
set
{
_myProperty = value;
}
}


is this possible? Or do I need the member variable to get it done?

Answer

You need a member variable and a full property declaration. Automatically implemented properties are only applicable if they're trivial wrappers around a field, with no logic involved. You can simplify your getter code slightly, btw:

get
{
    if (_myProperty == null)
    {
       _myProperty = XYZ;
    }
    return _myProperty;
}

(Note that none of this is thread-safe without extra locking, but I assume that's okay.)

By the way, you already have a private member variable if you're using automatically implemented properties - it's just that the compiler's generating it for you.