user3272018
user3272018

Reputation: 2419

Get property's name by PropertyInfo

I have a class like this:

public abstract class SomeClass<T> where T: new() {
    ...
    public void GetData() {
        ...
        var cur = new T();
        var properties = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
    ...
    }
}

where T can be something like

public class {
    ...
    public int SomeField {get; set;}
    ...
}

How can i get "SomeField" by properties?

If i call properties[i].Name i get "Int32".

There is RuntimePropertyInfo member in property, but i have no access to it.

Upvotes: 0

Views: 408

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062540

This works fine:

public class SomeType
{
    public int SomeField { get; set; }
}
class Program
{
    static void GetData<T>()
    {
        var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
        var firstPropertyName = properties[0].Name;
        Console.WriteLine(firstPropertyName);
    }
    static void Main()
    {
        GetData<SomeType>();
    }
}

I think you're accessing .PropertyType.Name rather than .Name.

Upvotes: 3

Related Questions