Alex Rivera | Logout

Problems with adding a `lazy` keyword to C#

Asked 2011-05-11T14:32:55.850
38

I would love to write code like this:

class Zebra
{
    public lazy int StripeCount
    {
        get { return ExpensiveCountingMethodThatReallyOnlyNeedsToBeRunOnce(); }
    }
}

EDIT: Why? I think it looks better than:

class Zebra
{
    private Lazy<int> _StripeCount;

    public Zebra()
    {
        this._StripeCount = new Lazy(() => ExpensiveCountingMethodThatReallyOnlyNeedsToBeRunOnce());
    }

    public lazy int StripeCount
    {
        get { return this._StripeCount.Value; }
    }
}

The first time you call the property, it would run the code in the get block, and afterward would just return the value from it.

My questions:

  1. What costs would be involved with adding this kind of keyword to the library?
  2. What situations would this be problematic in?
  3. Would you find this useful?

I'm not starting a crusade to get this into the next version of the library, but I am curious what kind of considerations a feature such as this should have to go through.

Edit
Report

1 Answer

3

If you don't mind using a post-compiler, CciSharp has this feature:

class Zebra {
  [Lazy] public int StripeCount {
    get { return ExpensiveCountingMethodThatReallyOnlyNeedsToBeRunOnce(); }
  } 
} 
answered 2011-07-05T16:33:23.140

Your Answer