Alex Rivera | Logout

Test if a Property is not Null before Returning

Asked 2010-03-25T14:31:07.217
31

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?

c#
Edit
Report

1 Answer

2

You need the member variable to get it done:

public class MyClass
{
    MyType _myProperty = null;

    public MyType MyProperty
    {    
        get
        {
            if(_myProperty == null)
                _myProperty = XYZ;

            return _myProperty;
        }
    }
}
answered 2010-03-25T14:33:51.297

Your Answer