2

I am looking for a solution to solve this problem I have.

I got an Object:

- Person (String ID, String FirstName, String LastName)

I got a List with a couple Persons

- List<Person> persons;

What my goal is:

1. Iterate through List
2. Get property value from that element with a string named to that property

For example:

I want to know the ID of the person in a list:

I can do this:

foreach(Person p in persons)
{
    String personId = p.ID;
}

But I want to do something like this:

foreach(Person p in persons)
{
    String personId = p. + "ID";
}

I want to append the string "ID" to get the ID of that element, instead of calling p.ID.

Is this possible? I need a solution for this, and I have spent a lot of time but couldn't find any solution on the internet.

Swag
  • 2,090
  • 9
  • 33
  • 63
  • 2
    Why would you want to do that? – khellang Mar 24 '14 at 10:54
  • 1
    You should use reflection, take a look at this SO [question](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp). – Alessandro D'Andria Mar 24 '14 at 10:54
  • @khellang I am reading a text file with ID's and Property names. I am getting the persons by their ID (read from the file) and put them in a list. Then I read the property names (string) from that file and iterate through the list that I've filled and get the property value of the element by the read strings from the file. – Swag Mar 24 '14 at 10:56
  • 1
    @AlessandroD'Andria: 99.9999999% of all questions that can be solved with reflection are just the wrong approach. If OP would say what he's actually trying to do we could help to find a better approach. – Tim Schmelter Mar 24 '14 at 10:57
  • @TimSchmelter i am not a big fan of reflection, but for what the OP is asking it's the only way, but you're right that the OP have to move a few steps back and rethink it's problem. – Alessandro D'Andria Mar 24 '14 at 11:02
  • This sounds like a serialization problem. Why don't you use some standardized form of serialization instead? JSON, XML, YAML, whatever :) – khellang Mar 24 '14 at 11:03
  • @AlessandroD'Andria: in 14 years of .NET i've never needed reflection in prodoction. So there's almost always a better way that is more readable, more maintainable, more efficient without using it. It's no wonder that mainly non experienced developers are asking questions which beg for reflection. – Tim Schmelter Mar 24 '14 at 11:07

2 Answers2

5

You could use reflection to get the value of a property by name:

foreach (Person p in persons)
{
    var personId = typeof(Person).GetProperty("ID").GetValue(p, null) as string;
}

Of course this needs some error handling and some null checks, but you get the gist :)

khellang
  • 17,550
  • 6
  • 64
  • 84
  • Thanks for your answer. So getting the property value by a string is called Reflection in c#? – Swag Mar 24 '14 at 11:00
  • @y451n Yes. You can read about `Type.GetProperty` [here](http://msdn.microsoft.com/en-us/library/kz0a8sxy.aspx). – khellang Mar 24 '14 at 11:02
1

As mentioned by other answers, the easiest way (although maybe not the best approach) is using reflection.

I've included support for base data types and string in the following class (and added an additional property to demonstrate how it can be used for base data types):

public class Person {
    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    private PropertyInfo GetProperty(string name) {
        PropertyInfo property = GetType().GetProperty(name);

        if (property == null) {
            throw new ArgumentException(string.Format("Class {0} doesn't expose a {1} property", GetType().Name, name));
        }

        return property;            
    }

    public string GetStringProperty(string name) {
        var property = GetProperty(name);
        return (string) property.GetValue(this, null);
    }

    public T GetProperty<T>(string name) {
        var property = GetProperty(name);
        return (T) property.GetValue(this, null);
    }
}

The GetProperty and GetStringProperty methods throw a ArgumentException if the property doesn't exist.

Sample usage:

Person person = new Person {
    ID = "1",
    FirstName = "First",
    LastName = "Last",
    Age = 31            
};

Console.WriteLine(person.GetStringProperty("FirstName"));
Console.WriteLine(person.GetProperty<int>("Age"));
Antonio
  • 71,651
  • 11
  • 148
  • 165