Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Closures to keep track of a variable: Good idea or dirty trick?
    primarykey
    data
    text
    <p>Ok, i have a need to be able to keep track of value type objects which are properties on another object, which cannot be done without having those properties implement an IObservable interface or similar. Then i thought of closures and the famous example from Jon Skeet and how that prints out 9 (or 10) a bunch of times and not an ascending order of numbers. So i thought why not do this:</p> <pre><code>Class MyClass { ... Func&lt;MyValueType&gt; variable; ... public void DoSomethingThatGetsCalledOften() { MyValueType blah = variable(); //error checking too not shown for brevity //use it } ... } ... in some other consuming code ... MyClass myClass = new MyClass(); myClass.variable = () =&gt; myOtherObject.MyOtherProperty; //then myClass will get the current value of the variable whenever it needs it </code></pre> <p>Obviously this would require some understanding of how closures work, but my question is this: <strong>is this a good idea or a dirty hack and a misuse of the closure system?</strong></p> <p><strong>Edit:</strong> Since some people seem to be misunderstanding what i'm trying to say, here's a console program which demonstrates it:</p> <pre><code>using System; using System.Linq; namespace Test { class Program { public static void Main() { float myFloat = 5; Func&lt;float&gt; test = () =&gt; myFloat; Console.WriteLine(test()); myFloat = 10; Console.WriteLine(test()); Console.Read(); } } } </code></pre> <p>That will print out <code>5</code> then <code>10</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload