Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I get object instance from ()=>foo.Title expression
    primarykey
    data
    text
    <p>I have a simple class with a property</p> <pre><code>class Foo { string Title { get; set; } } </code></pre> <p>I am trying to simplify data binding by calling a function like</p> <pre><code>BindToText(titleTextBox, ()=&gt;foo.Title ); </code></pre> <p>which is declared like</p> <pre><code>void BindToText&lt;T&gt;(Control control, Expression&lt;Func&lt;T&gt;&gt; property) { var mex = property.Body as MemberExpression; string name = mex.Member.Name; control.DataBindings.Add("Text", ??? , name); } </code></pre> <p>so what do I put in <code>???</code> for the instance of my <code>Foo</code> class. How do I get a refernce to the calling <code>foo</code> instance from the lambda expression?</p> <p><strong>edit:</strong> The instance should be there somewhere because I can call <code>property.Compile()</code> and create a delegate that uses the <code>foo</code> instance inside my <code>BindToText</code> function. So my question is if this can be done without adding a reference to the instance in the function parameters. I call upon <a href="http://en.wikipedia.org/wiki/Occam&#39;s_razor" rel="nofollow noreferrer">Occum's Razor</a> to yield the simplest solution.</p> <p><strong>edit 2:</strong> What many have failed to notice is the <em>closure</em> that exists in accessing the instance of <code>foo</code> inside my function, if I compile the lambda. How come the compiler knows where to find the instance, and I don't? I insist that there has to be an answer, <em>without</em> having to pass an extra argument.</p> <hr> <h2>Solution</h2> <p>Thanks to <a href="https://stackoverflow.com/users/46594/virtualblackfox">VirtualBlackFox</a> the solution is such:</p> <pre><code>void BindText&lt;T&gt;(TextBoxBase text, Expression&lt;Func&lt;T&gt;&gt; property) { var mex = property.Body as MemberExpression; string name = mex.Member.Name; var fex = mex.Expression as MemberExpression; var cex = fex.Expression as ConstantExpression; var fld = fex.Member as FieldInfo; var x = fld.GetValue(cex.Value); text.DataBindings.Add("Text", x, name); } </code></pre> <p>which alows me to simply type <code>BindText(titleText, () =&gt; foo.Title);</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.
    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