Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a Property is not Null before Returning

Tags:

c#

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?

like image 895
DaveDev Avatar asked Mar 25 '10 14:03

DaveDev


People also ask

What does if NULL return?

The IFNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.

IS NULL check in C#?

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.


1 Answers

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.

like image 181
Jon Skeet Avatar answered Sep 30 '22 15:09

Jon Skeet