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, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With