Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop on field names of a class

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

like image 679
Dr. Rajesh Rolen Avatar asked Sep 10 '10 10:09

Dr. Rajesh Rolen


5 Answers

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; });
like image 82
Marc Gravell Avatar answered Oct 23 '22 15:10

Marc Gravell


Try this:

var t = typeof(YourTypeHere);
List<string> fieldNames = new List<string>(t.GetFields().Select(x => x.Name));
like image 30
StuffHappens Avatar answered Oct 23 '22 15:10

StuffHappens


try

    public static string[] GetFieldNames(Type t)
    {
        FieldInfo[] fieldInfos = t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        return fieldInfos.Select(x => x.Name).ToArray();
    }
like image 3
Aliostad Avatar answered Oct 23 '22 14:10

Aliostad


This work for me perfectly ExampleClass is class You need list all fields

public void GetClassFields(Type t)
{
    List<string> fieldNames = new List<string>(t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(x => x.Name));
    foreach (string name in fieldNames)
    {
        Console.WriteLine(name);
    }       
}
//Usage
GetClassFields(typeof(ExampleClass));
like image 1
mbahojlo Avatar answered Oct 23 '22 15:10

mbahojlo


Worked for me

var t = typeof(YOURTYPE);

var allfieldNames = new List<string>(t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Select(x => x.Name));

// t for Type

like image 1
Usman Younas Avatar answered Oct 23 '22 14:10

Usman Younas