Use string as argument for GetValue()

I have a class Player, and an instance of that class called player. Inside that class, I have an auto-property called Name.

I need to access the property Name from the instance. I already know of other ways to do this, but because of what I want this program to do, I need to do it via:

var type= Type.GetType("GameSpace.Player")
var property = type.GetProperty("Name");
var propVal = property.GetValue(player);

Console.WriteLine(propVal);

This code works perfectly fine. The issue here is that sometimes, I will need to change the name of the instance, which in this case is player. I thought of making a string to hold the name of the instance.

string instanceName = "player";
enter code here
var type= Type.GetType("GameSpace.Player")
var property = type.GetProperty("Name");
var propVal = property.GetValue(instanceName);

Console.WriteLine(propVal);

But this doesn't working, throwing the error that GetValue doesn't have an overload that allows a string value.

Is there a way to accomplish what I am asking for. I know that I can simply do Console.WriteLine(player.Name), but in this case that is not an options, mostly because the arguments (name of instance) are stored in an XML file.

EDIT 1: Error Message:

enter image description here

Jon Skeet
people
quotationmark

Instances don't have names, generally. (You can create a class with a Name property, but that's nothing the framework is going to care about.) The value you have to pass to PropertyInfo.GetValue is a reference to the object whose property you want to fetch. Passing a name makes no sense to the framework. (Apart from anything else, it has no context - there could be lots of variables with that name in all kinds of places.)

Variables have names. If the name you've got refers to a local variable, you're out of luck - but if the name you've got refers to a field, you can get at that field via reflection. Get the right FieldInfo, then get the value of that.

However, it may well be better just to have a Dictionary<string, object> mapping the names you might run into in the XML file into the appropriate objects you want to fetch properties for. Alternatively, you could have a switch statement to get at the right value - it really depends on the context.

Generally, tying your class implementation (field names) to an XML file is a bad idea, IMO.

people

See more on this question at Stackoverflow