Daniel Eugen
Daniel Eugen

Reputation: 2780

Dynamically Getting Property Value From Class

I have a class which i want to retrieve a property from it dynamically

here is a sample from the class

namespace TEST
{
    public class Data
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

i am trying to use GetProperty but it always return null

static object PropertyGet(object p, string propName)
{
    Type t = p.GetType();
    PropertyInfo info = t.GetProperty(propName);
    if (info == null)
        return null;
    return info.GetValue(propName);
}

like this

    var data = new Data();

    var x = PropertyGet(data, "Username");
    Console.Write(x?? "NULL");

Upvotes: 0

Views: 106

Answers (2)

MrMoDoJoJr
MrMoDoJoJr

Reputation: 410

This works:

public class Data
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class Program
{
    static object PropertyGet(object p, string propName)
    {
        Type t = p.GetType();
        PropertyInfo info = t.GetProperty(propName);

        if (info == null)
        {
            return null;
        }
        else
        {
            return info.GetValue(p, null);
        }
    }

    static void Main(string[] args)
    {
        var data = new Data() { Username = "Fred" };

        var x = PropertyGet(data, "Username");
        Console.Write(x ?? "NULL");
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500755

This line is wrong, and should be throwing an exception for you:

return info.GetValue(propName);

You need to pass in the object from which to extract the property, i.e.

return info.GetValue(p);

Also note that currently data.Username is null. You want something like:

var data = new Data { Username = "Fred" };

I've validated that with these two changes, it works.

Upvotes: 2

Related Questions