C#: how to return a list of the names of all properties of an object?

I have a class:

 public class foo
{
    public IEnumerable<string> stst_soldToALTKN { get; set; }
    public int sId { get; set; }        
    public string stst_LegalName { get; set; }
    public string stst_TradeName { get; set; }
    public string stst_StreetAddress { get; set; }
}

Is there a method I can call that would return a list/ienumerable of the names of each property???

For Example:

blah foo1 = new foo();
ienumerable<string> foo1List = GetAllPropertyNames(foo1);
foo1List.ToList();

Result: 'stst_soldToALTKN', 'sId', 'stst_LegalName', 'stst_TradeName', 'stst_StreetAddress'

Upvotes: 0

Views: 179

Answers (4)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107536

You can use reflection to get a list of the properties and from them, select the name:

var foo1 = new foo();
var propertyNames = foo1.GetType()
    .GetProperties(BindingFlags.Public | BindingFlag.Instance)
    .Select(p => p.Name)
    .ToList();

propertyNames will now be a List<string>.

BTW, you don't need an instance of foo for this to work. You can get its type instead by doing:

var propertyNames = typeof(foo)
    .GetProperties(BindingFlags.Public | BindingFlag.Instance)
    .Select(p => p.Name)
    .ToList();

Upvotes: 0

Mike Schwartz
Mike Schwartz

Reputation: 2212

You could try

var propertyNames = foo1.GetType()
                   .GetProperties()
                   .Select(x => x.Name).ToList();

Upvotes: 1

D Stanley
D Stanley

Reputation: 152556

var propNames = foo1.GetType()
                    .GetProperties()
                    .Select(pi => pi.Name)

Upvotes: 2

Clay Fowler
Clay Fowler

Reputation: 2078

You can use this:

public IEnumerable<string> GetAllPropertyNames(object o)
{
    foreach (PropertyInfo propInfo in o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
    yield return propInfo.Name;
}

Upvotes: 0

Related Questions