0

I saw a code like this:

readonly Lazy<SomeEnum> _somevar;

What's the advantage of using Lazy over an enumeration? Enum itself is small.

Ajay
  • 16,823
  • 9
  • 50
  • 94

2 Answers2

2

As there seems to be some confusion why this might be a good idea, here is a version doing the same without Lazy:

private SomeEnum? _value = null;

private SomeEnum CostyCalculation()
{
    return ...;
}

public SomeEnum MyVar
{
   get 
   {
      if (_value == null)
          _value = CostyCalculation();
      return _value.Value;
   }
}

As you can see the value is only calculated when you first need it and once you have it you don't need to recalculate it again.

Lazy does the same thing with a slight different syntax/usage:

    private Lazy<SomeEnum> _value = new Lazy<SomeEnum>(CostyCalculation);

    private SomeEnum CostyCalculation()
    {
        return SomeEnum.E1;
    }

    public SomeEnum MyVar
    {
        get 
        {
            return _value.Value;
        }
    }
Ajay
  • 16,823
  • 9
  • 50
  • 94
Carsten
  • 49,407
  • 9
  • 85
  • 111
0

Lazy is useful in situations when you need to right now declare creation of some object, that will consume pretty many time or/and resources during initialization, and you sure that in most situations you don't realty need it during program execution.

For example, you have object that during creation downloads some webpages, parse it, download every subpage, parse it, and then stores some statistical data into self. This will consume pretty much time.. But you want to declare object now, and maybe, only maybe use it latter. You can wrap it into Lazy<T>, so this object maybe, only maybe will be initialized latter - when you do first access to it.

This is only advantage of using Lazy over just creating object without it.

rufanov
  • 2,853
  • 1
  • 17
  • 37