简体   繁体   中英

How to nicely call property with side effects?

This is purely a language matter, because I know, that this may (and possibly even should) be solved in a different way .

We have a property Prop , which in its getter has some side effects. How to "call" this property in a "nice" way to trigger these side effects?

One way:

object dummy = this.Prop;

But this doesn't seem to be a nice solution, because it involves creating unnecessary variable. I tried with:

(() => this.Prop)();

But it doesn't compile. Is there short and clean way to do it?

If you create a variable, you'll then get code complaining that it's unused, which can be annoying.

For benchmarking cases, I've sometimes added a generic Consume() extension method, which just does nothing:

public static void Consume<T>(this T ignored)
{
}

You can then write:

this.Prop.Consume();

and the compiler will be happy. Another alternative would be to put have a method which accepted a Func<T> :

public static void Consume<T>(Func<T> function)
{
    function();
}

Then call it as:

Consume(() => this.Prop);

I rarely face this situation outside tests (both benchmarks, and "I should be able to call the property without an exception being thrown" test) but every so often it can be useful, eg to force a class to be initialized. Any time you find yourself wanting this, it's worth considering whether this would be more appropriate as a method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM