views:

110

answers:

3

I have got a class which contains more then 150 fields. i need the name of fields (not value) in an array.

because its very hard and not a good approach to write 150 fields name (which can be incremented or decremented in count according to requirement change) manually in code.

i need help to get loop through names for field or get list of field names in a array so that i can loop over it and use it in code. i am using visual studio 2008

Thanks

+12  A: 

for all public + nonpublic instance fields:

var fields = typeof(YourType).GetFields(
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var names = Array.ConvertAll(fields, field => field.Name);

or in VS2005 (comments):

FieldInfo[] fields = typeof(YourType).GetFields(
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
string[] names = Array.ConvertAll<FieldInfo, string>(fields,
    delegate(FieldInfo field) { return field.Name; });
Marc Gravell
hi marc. its really good solution. can you please tell me that. is it same for visual studio 2005 or there will be other syntex?
Rajesh Rolen- DotNet Developer
actaully i have got a same application of previous version in vs2005
Rajesh Rolen- DotNet Developer
There's a small difference. You can't user ConvertAll in vs 2005, so you should use foreach instead. And also use concrete type instead of var.
StuffHappens
@Rajesh, @StuffHappens You *should* be able to use ConvertAll, but the syntax will be more verbose - will update
Marc Gravell
+2  A: 

try

    public static string[] GetFieldNames(Type t)
    {
        FieldInfo[] fieldInfos = t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        return fieldInfos.Select(x => x.Name).ToArray();
    }
Aliostad
+5  A: 

Try this:

var t = typeof(YourTypeHere);
List<string> fieldNames = new List<string>(t.GetFields().Select(x => x.Name));
StuffHappens