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?
2 Answers 2
?? 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<T>
.
private Lazy<string> lazyStringField = new Lazy<string>(GetStringField);
protected string StringField
{
get
{
return lazyStringField.Value;
}
}
-
\$\begingroup\$ I'm aware of the ?? operator; what I've never seen before was it being glued together with an assignment statement like that before. \$\endgroup\$Dan Is Fiddling By Firelight– Dan Is Fiddling By Firelight2013年01月11日 20:01:08 +00:00Commented Jan 11, 2013 at 20:01
-
\$\begingroup\$ How much slower is this code? \$\endgroup\$Leonid– Leonid2013年01月14日 00:57:12 +00:00Commented Jan 14, 2013 at 0:57
-
4\$\begingroup\$ While I'd agree that normally
??
doesn't confuse, I'd argue that it's usage here combined with the rarely-used side effect of=
which returns the value just set is confusing. \$\endgroup\$Bobson– Bobson2013年01月14日 21:05:44 +00:00Commented Jan 14, 2013 at 21:05 -
\$\begingroup\$ lazy properties are not supported in CF and should be implemented manually \$\endgroup\$hellboy– hellboy2014年01月28日 14:47:57 +00:00Commented Jan 28, 2014 at 14:47
I noticed that ReSharper's suggestion too and I decided to turn it off. I think that an expression should be used either for its value or for its side-effects, but not both. If you do both, your code will be more confusing. This principle is known as command-query separation.
And I agree with others that using Lazy<T>
is even better. If you're still on .Net 3.5 (or older), it shouldn't be that hard to write your own version of that class.
-
\$\begingroup\$ I've turned off that suggestion as well. Sometimes ReSharper's suggestions make the code less intuitive... \$\endgroup\$Bobson– Bobson2013年01月14日 19:47:08 +00:00Commented Jan 14, 2013 at 19:47
Lazy<T>
, I still tend to use this approach in most cases. Choose whichever feels simpler to you and don't worry about confusing other people. I totally agree with @dreza here: That piece of code is clear enough for someone who saw something like that for the first time to get it in one minute. \$\endgroup\$