I really cannot see the point of it, but this may be one approach. The method below uses reflection to loop over all properties of the type, fetch the value for each property and use ReferenceEquals to check whether the property references the same object as the one requested:
private string _myProperty = "TEST";
public string MyProperty
{
get
{
return _myProperty;
}
}
public string GetName(object value)
{
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < properties.Length; i++)
{
object propValue = properties[i].GetValue(this, null);
if (object.ReferenceEquals(propValue,value))
{
return properties[i].Name;
}
}
return null;
}
Console.WriteLine(GetName(this.MyProperty)); // outputs "MyProperty"
This is far from failsafe though. Let's say that the class has two string properties, MyProperty and YourProperty. If we at some point do like this: this.MyProperty = this.YourProperty
they will both reference the same string instance, so the above method cannot with certainty determine which property that is the wanted one. As it is written now it will return the first one it finds in the array.