Note that there are some explanatory texts on larger screens.

plurals
  1. POClass member as a first-class object
    text
    copied!<p>I was wondering if there is something in c# to be able to pass a member of a class to another function that will use this member to get a value. So get a value of a field determined only which one at runtime. Something like in other languages (PHP at least I think) that you can do</p> <pre><code>a.b = "something" </code></pre> <p>but also</p> <pre><code>a["b"] = "something"; </code></pre> <p>edit: actually not so good an example since a string is used, sorry</p> <p>For clarity an example of what I'd like to be able to do:</p> <pre><code>class A { int x; int y; } void somethingsomething&lt;T&gt;(T class, SomeMagicFieldClass f) { dosomethingwith(somemethodthatgivesmethevalueoffield(class, f)); } </code></pre> <p>Where then I can call the method like this:</p> <pre><code>A a = new A(); somethingsomething(a, A.x); //hypothetical notation somethingsomething(a, A.y); </code></pre> <p>I now have something similar where I do:</p> <pre><code>somethingsomething(a, "x"); somethingsomething(a, "y"); </code></pre> <p>I then go find the field using introspection API (also trying GetProperty)</p> <pre><code>MemberInfo memberInfo = item.GetType().GetField(fieldName); </code></pre> <p>This works but the disadvantage is that the fields passed as a string won't get updated when "refactoring" fieldnames in visual studio, so I was thinking maybe there exists something like this in c# that would get refactored automatically when changing field names?</p> <p>Thanks a lot for reading this boring question</p>
 

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