0

How would I "package" an instances field in a func or action by method?

What other possibilities are there for keeping references to a specific (value or reference) field in another class? (I know I can just keep a reference to the object itself)

The following is pseudo-code and will not compile.

class TestClass
{

    private static bool someField;

    private Func<bool> FuncPackage (ref bool field)
    {
        return () => ( return field; );
    }

    private void DoSomethingWithPackage (Func<bool> package)
    {
        if(package())
            Console.WriteLine ("true");
        else
            Console.WriteLine ("false");
    }

    static void Main(string[] args)
    {
        someField = false;
        Func<bool> package = FuncPackage (ref someField);
        DoSomethingWithPackage (package);
    }

}
user2994682
  • 503
  • 1
  • 8
  • 19
  • 1
    Can you explain why simple `()=> this.someField;` does not work? Or equivalent with reflection/[expression](http://stackoverflow.com/questions/321650/how-do-i-set-a-field-value-in-an-c-sharp-expression-tree)? – Alexei Levenkov Mar 05 '14 at 19:16
  • 1
    What problem you're trying to solve with this? There might be a better way – Sriram Sakthivel Mar 05 '14 at 19:19
  • I wanted to keep a reference to a field to query later, obviously I could just keep a reference to the object (and with interfaces I could standardize against a property). – user2994682 Mar 06 '14 at 22:46
  • @AlexeiLevenkov i wanted to pass in a field from any other object not just this instance. – user2994682 Mar 06 '14 at 22:47

1 Answers1

4

This is inherently impossible.

You're asking to create a closure class that captures a reference to the field from the original class.

C# can't do that.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964