Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest C# code to poll a property?

Tags:

c#

properties

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.

like image 415
Protector one Avatar asked Nov 29 '22 10:11

Protector one


2 Answers

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.

like image 37
Ed S. Avatar answered Dec 14 '22 17:12

Ed S.


(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...

like image 179
Jon Skeet Avatar answered Dec 14 '22 15:12

Jon Skeet