wmash
wmash

Reputation: 4202

Get member variable via other variable name C#

I wasn't sure how else to title this question.
I am trying to retrieve member variables of a class via another variable. Let me explain with an example.

This is my code where I am trying to access the value of a member variable in the Network class.
(item is NOT the name of the variable I am trying to access. item holds the string of the variable I am trying to access)

private void addKeyValuePairRow(string item) {
    addRow(item);
    addKeyLabel(item, false);
    addValueLabel(item);

    if (item.Contains("_"))
        item = item.Replace("_", "");

    setValue(Network[item]);
}

Network class:

public class Network {
    public string DefaultGateway { get; set; }
    public string ExternalIP { get; set; }
    public string SSID { get; set; }
    public string NetworkConnection { get; set; }
    public string NetworkConnectionType { get; set; }
    public string InternetConnection { get; set; }

    ...
}

So say I am trying to get DefaultGateway, this would be my code calling the method:

addKeyValuePairRow("Default_Gateway");

I feel like this would be a relatively simple task but cannot find anything on it.

Any help appreciated.

Upvotes: 0

Views: 160

Answers (1)

Damian Green
Damian Green

Reputation: 7495

Something like

var src = new Network();
setValue(src.GetType().GetProperty(item).GetValue(src, null));

You've not defined where your Network class is instantiated anywhere in your question however.

Upvotes: 3

Related Questions