1

Is it possible to use a variable to access a List field using c# as in the following?

string myField = "ImmediateAddress";
byte returnByte = mnemonicList[0].myField;
4
  • 1
    What do you want to achieve? Commented Jun 3, 2016 at 18:22
  • And what type is mnemonicList? Commented Jun 3, 2016 at 18:22
  • "Yes, but not very efficiently" (unless the type exposes a keyed API) Commented Jun 3, 2016 at 18:28
  • mnemonicList is a list of class Mnemonics. What I am trying to do is refactor my code from six method calls to a single method. Each method performs the same result with the exception of the lookup in the list. i.e. returnByte in my snippet. Commented Jun 3, 2016 at 18:37

2 Answers 2

1

using reflection you can access fields at run time, and don't forget to add validations

mnemonicList[0].GetType().GetProperty(myField).GetValue(mnemonicList[0], null);
Sign up to request clarification or add additional context in comments.

1 Comment

Hmmmm, Thought I had this but when it tried to return an int field within my list it doesn't work. Seems that the GetProperty(myField) wants a string. I have tried casting myField to no avail. Any ideas?
0

I'm not sure if this is much help - but instead of a List, you could use a dictionary instead. Let me know if I'm suggesting the wrong solution, but this way you can access entries with objects like string, like dictObject["keyToValue"]. It does require you to use a Dictionary instead of a List, but if you want to do find things with a string, it's the easiest solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.