I have an extension method which takes a parameter. Inside the extension method I want to get access to the name of the object which was passed in.
static MyObject Add<T>(this MyObject myObj, T value) {
// MyObject is dictionary<string, object> for simple example
myObj.Add(nameof(value), value);
return myObj;
}
void run() {
var anotherObject = new AnotherObject() { Name = "Bob" };
var myObject = new MyObject().Add(anotherObject.Field);
}
When this executes it puts "value", "Bob"
whereas i want it to put "Name", "Bob"
in the dictionary.
Is this possible using the nameof()
function or do I need to re-think the logic? The only thing i can come up with to preserve the general idea is:
static MyObject Add<T>(this MyObject myObj, string name, T value)...
myObject.Add(nameOf(anotherObject.Field), anotherObject.Field);
I didn't like having to repeat the field definition.