Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to nicely call property with side effects?

Tags:

c#

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?

like image 564
Spook Avatar asked Mar 20 '23 14:03

Spook


1 Answers

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, e.g. 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.

like image 177
Jon Skeet Avatar answered Mar 28 '23 11:03

Jon Skeet