I would like to know the simplest code for polling a property's value, to execute the code in its getter.
Currently I'm using: instance.property.ToString();
, but I'd rather have something without possible side-effects or unnecessary overhead.
That sounds to me like a really terrible idea. Honestly, if you have logic in a getter that needs to be executed regularly, take it out of the getter and stick it in a method. I would hate to jump in and maintain code like that, and once I finally figured out why it was doing what it does I would refactor it.
(I'm assuming you're trying to avoid the warning you get from simply assigning the value to an unused variable.)
You could write a no-op extension method:
public static void NoOp<T>(this T value)
{
// Do nothing.
}
Then call:
instance.SomeProperty.NoOp();
That won't box the value or touch it at all - just call the getter. Another advantage of this over ToString
is that this won't go bang if the value is a null reference.
It will require JIT compilation of the method once per value type, but that's a pretty small cost...
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