C# Get Highest variable name
Is there a more elegant way of getting the variable name with the highest value besides making a wall of if statements? (not the variable value, but the variable name).
Im not looking for code, but if you know a function I'll be good from there. All Linq and Mathf functions I've seen only return the value, not the variable name.
Answer by UnityCoach · Feb 27, 2017 at 05:31 PM
If they're all of the same type, you may use a Dictionary<string, float>
, and sort it by the value.
To dumb this down a bit, ins$$anonymous$$d of using individual variables x, y, z, the trick is to make one list of variables, usually an array. Once you do that, you don't need the name of the variable - just the slot#. If the highest is in slot 3, easy to get it using A[3].
If you don't know arrays, the regular internet probably has a decent explanation (or my taxesforcatses site has a chapter.)
Not sure why I didn't think of using a Dictionary. Thanks UnityCoach!
Answer by Glurth · Feb 27, 2017 at 06:32 PM
I don't know if I would classify it as elegant, but you can use reflection to do this.
MemberInfo[] members= typeof(YourClassThatContainsMembersToCompare).GetMembers();
the members array will now contain all members of the class. You will probably want to filter this array, to compare only the members you want.
You can get the name of each member using the "name" property of the member info.
Getting the VALUE in each member, for your (highest) comparison, is a bit trickier, as you will need to check the MemberType to determine if the member is a "property" or a "field" (or neither), and cast your MemberInfo to the appropriate sub-class: FieldInfo OR PropertyInfo
Now, you can use THAT class's GetValue(object)
function, to get the member value. (The object
parameter is the object that contains the member you want to examine.)
You can also use the derived class to get the underlying type of the member, using FieldType and PropertyType. This could be useful if say... you only wanted to compare float values.
https://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.getvalue(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/hh194385(v=vs.110).aspx
Your answer
Follow this Question
Related Questions
Problem while using several tags in a OnTriggerEnter (Collider other) 0 Answers
Can't seem to find a proper stepping stone to learn from, any ideas? 3 Answers
Use of unassigned local variable 'startPos' " & " Use of unassigned local variable 'endPos' 1 Answer
Animator Parameter not linking to script variable 0 Answers
Help with converting small pseudo script to C# please? 0 Answers