patterncsharpModerate
Lazy loaded property readability
Viewed 0 times
loadedpropertylazyreadability
Problem
I currently have code that looks like this
ReSharper is suggesting I change the property to:
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?
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
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.