Resharper offering "convert to expression", but how?

Using Resharper 7.1.1 in Visual Studio 2012. Sample code:

    private string _str;

    private string TheString
    {
        get
        {
            if (_str == null) // "X"
            {
                _str = GetString();
            }
            return _str;
        }
    }

    // do some work to get string. e.g. read from database
    private string GetString()
    {
        return "blah";
    }

On a line labeled “X,” resharper underlines the “if” statement and suggests “Convert to Expression.” But how? Did I miss something?

+4
source share
3 answers

Given your code,

Click "if," which says he wants to use

press ALT-ENTER

or click on the light bulb

he will have the opportunity to convert either press the enter key, or click on it with the mouse, and you will get

        private string _str;

        private string TheString
        {
            get { return _str ?? (_str = GetString()); }
        }
+7
source
Kate pretty much answered your question. Here's a screenshot of a light blub -

enter image description here

enter image description here

+3

, , Lazy<T>:

using System;

class Foo
{
    private readonly Lazy<string> _str;

    public Foo()
    {
        _str = new Lazy<string>(GetString);
    }

    private string TheString
    {
        get
        {
            return _str.Value;
        }
    }

    private string GetString()
    {
        return "blah";
    }
}

TheString , , , make-if-not-set, _str.Value .

( Lazy.)

+1

All Articles