Reputation: 127
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
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
Reputation: 2212
You could try
var propertyNames = foo1.GetType()
.GetProperties()
.Select(x => x.Name).ToList();
Upvotes: 1
Reputation: 152556
var propNames = foo1.GetType()
.GetProperties()
.Select(pi => pi.Name)
Upvotes: 2
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