HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Lazy loaded property readability

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
loadedpropertylazyreadability

Problem

I currently have code that looks like this

private string _stringField;

protected string StringField
{
    get
    {
        if (_stringField == null)
            _stringField = GetStringField();
        return _stringField;
    }
}


ReSharper is suggesting I change the property to:

protected string StringField
{
    get
    {
        return _stringField ?? (_stringField = GetStringField());
    }
}


This isn't an idiom I've seen before and probably would have to think about the first time I saw it; is this something I should be concerned would confuse other people too?

Solution

?? is well known operator in C#. It doesn't confuse but reduce coding.

Both snippets have same meaning.

But if it is .NET 4.0 onwards, i would rather use Lazy.

private Lazy lazyStringField = new Lazy(GetStringField);
protected string StringField
{
    get
    {
        return lazyStringField.Value;
    }
}

Code Snippets

private Lazy<string> lazyStringField = new Lazy<string>(GetStringField);
protected string StringField
{
    get
    {
        return lazyStringField.Value;
    }
}

Context

StackExchange Code Review Q#20440, answer score: 16

Revisions (0)

No revisions yet.