I want to use System.Lazy to Lazy Initialization of my List in my Entites:
public class Questionary
{
private Lazy<List<Question>> _questions = new Lazy<List<Question>>(() => new List<Question>());
public IList<Question> Questions { get { return _questions.Value; } set { _questions.Value = value; } }
}
The problem is on my SETTER, get this error: The property 'System.Lazy<T>.Value
' has no setter
If i want to do MyInstance.Questions = new List<Question> { ... }
?
How do I proceed?
Update:
I'm trying to avoid that:
private IList<Question> _questions;
//Trying to avoid that ugly if in my getter:
public IList<Question> Questions { get { return _questions == null ? new List<Question>() : _questions; } set { _questions = value } }
I'm doing something wrong?
You could do something like this:
public class Questionary
{
private Lazy<IList<Question>> _questions =
new Lazy<IList<Question>>(() => new List<Question>());
public IList<Question> Questions
{
get { return _questions.Value; }
set { _questions = new Lazy<IList<Question>>(() => value); }
}
}
However, I don't see why you need Lazy<T>
here at all. There is no benefit in using it, because the initialization of a new List<T>
should be the same as the initialization of a new Lazy<T>
...
I think it would be enough to keep it as simple as this:
public class Questionary
{
private IList<Question> _questions = new List<Question>();
public IList<Question> Questions
{
get { return _questions; }
set { _questions = value; }
}
}
or
public class Questionary
{
public Questionary()
{
Questions = new List<Question>();
}
public IList<Question> Questions { get; set; }
}