Test if a Property is not Null before Returning

Posted by DaveDev on Stack Overflow See other posts from Stack Overflow or by DaveDev
Published on 2010-03-25T14:31:07Z Indexed on 2010/03/25 14:33 UTC
Read the original article Hit count: 599

Filed under:

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

© Stack Overflow or respective owner

Related posts about c#