Question

This is the syntax for a Field which is lazy initialized.

public class MyClass
{
    string _cat;
    public MyClass(string Category)
    {
        _cat=Category;
    }

    MyExpensive _expensive;
    public MyExpensive Expensive
    {
        get 
        {
            LazyInitializer.EnsureInitialized(ref _expensive, () = > new MyExpensive ());
            return _expensive;
        }
    }
}

But what if I need to create new MyExpensive with a run-time ctor params ? (according to a flow logic)

I don't want to create a flag field and then in do a lot's of IF's

I mean ,sometimes I need to run new MyExpensive ("picture") and sometimes new MyExpensive ("flowers")

How can I do that ?

(exclude creating a lazy field for each category - )

Was it helpful?

Solution

If you are doing anything expensive, you should do it in a method, not a property.

Properties should be fast and inexpensive as this is the normal expectation by most programmers (principle of least astonishment).

In your case, don't have a getter - use:

public MyExpensive GetExpensive()
{
    LazyInitializer.EnsureInitialized(ref _expensive, () = > new MyExpensive ());
    return _expensive;
}

And of course, you have have parameterized overloads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top