I would like to know how to get the name of the property that a method parameter value came from. The code snippet below shows what I want to do:
Person peep = new Person(); Dictionary<object, string> mapping = new Dictionary<object, string>(); mapping[peep.FirstName] = 'Name'; Dictionary<string, string> propertyToStringMapping = Convert(mapping); if (mapping[peep.FirstName] == propertyToStringMapping['FirstName']) Console.WriteLine('This is my desired result'); private Dictionary<string, string> Convert(Dictionary<object, string> mapping) { Dictionary<string, string> stringMapping = new Dictionary<string, string>(); foreach (KeyValuePair<object, string> kvp in mapping) { //propertyName should eqal 'FirstName' string propertyName = kvp.Key?????? stringMapping[propertyName] = kvp.Value; } return stringMapping; }
I think ultimately you will need to store either the PropertyInfo object associated with the property, or the string representation of the property name in you mapping object. The syntax you have:
Would create an entry in the dictionary with a key value equal to the value of the peep.FirstName property, and the Value equal to ‘Name’.
If you store the property name as a string like:
You could then use reflection to get the ‘FirstName’ property of your object. You would have to pass the ‘peep’ object into the Convert function, however. This seems to be somewhat opposite of what you are wanting to do.
You may also be able to get crazy with Expressions and do something like:
Then in your Convert function you could examine the expression. It would look something like:
This is more or less off the top of my head, so I may have the expression types off a bit. If there are issues with this implementation let me know and I will see if I can work out a functional example.