Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all the public fields of an object in C#?

I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList.

Currently my code is as follows:

public static void ListArrayListMembers(ArrayList list)
    {
        foreach (Object obj in list)
        {
            Type type = obj.GetType();
            string field = type.GetFields().ToString();
            Console.WriteLine(field);

        }
    }

Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. I'll fix this later - right now I'm just curious how to get all of the public fields associated with an object.

like image 460
junkforce Avatar asked Oct 26 '08 00:10

junkforce


People also ask

What are fields in objects?

A field is one data point within an object (e.g. “First Name” on the lead object). A record is row of field data within an object (e.g. the lead “John Smith”). An object is comprised of its field definitions and records. A tab is used to expose an object and its data to the end user through the web interface.

What are fields of a class?

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type. A class or struct may have instance fields, static fields, or both.

What is a field in C sharp?

A field, in C#, is a member of a class or an object of any type that represents a memory location for storing a value. Fields are used to store data that must be accessible to multiple methods of a class and available throughout the lifetime of an object.

What is field in object oriented programming?

In object-oriented programming, a field (also called data member or member variable) is a particular piece of data encapsulated within a class or object.


4 Answers

foreach (Object obj in list) {
    Type type = obj.GetType();

    foreach (var f in type.GetFields().Where(f => f.IsPublic)) {
        Console.WriteLine(
            String.Format("Name: {0} Value: {1}", f.Name, f.GetValue(obj));
    }                           
}

Note that this code requires .NET 3.5 to work ;-)

like image 114
Dave Markle Avatar answered Oct 10 '22 17:10

Dave Markle


You can obtain all the object Fields declared directly in the class with the BindingFlags:

GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)

and all object Fields including inherited with:

GetFields(BindingFlags.Public | BindingFlags.Instance)
like image 41
Jonathan Webb Avatar answered Oct 10 '22 17:10

Jonathan Webb


public static void ListArrayListMembers(ArrayList list)
{
    foreach (Object obj in list)
    {
        Type type = obj.GetType();
        Console.WriteLine("{0} -- ", type.Name);
        Console.WriteLine(" Properties: ");
        foreach (PropertyInfo prop in type.GetProperties())
        {
            Console.WriteLine("\t{0} {1} = {2}", prop.PropertyType.Name, 
                prop.Name, prop.GetValue(obj, null));
        }
        Console.WriteLine(" Fields: ");
        foreach (FieldInfo field in type.GetFields())
        {
            Console.WriteLine("\t{0} {1} = {2}", field.FieldType.Name, 
                field.Name, field.GetValue(obj));
        }
    }
}

I'd like to mention that looking for IsPublic in the fields is not necessary as type.GetFields() as defined by MSDN states:

Return Value - Type: System.Reflection.FieldInfo[]

An array of FieldInfo objects representing all the public fields defined for the current Type.

like image 29
nyxtom Avatar answered Oct 10 '22 17:10

nyxtom


Of course, another question would be "why have you got public fields?" - properties being preferable. As an abstraction, note that reflection isn't the only option: it is also possible for a type to expose it's properties on-the-fly at runtime (like how an untyped DataTable/DataView exposes columns as properties).

To support this (while also supporting simple objects), you would use TypeDescriptor:

        foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
        {
            Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
        }

This also allows for numerous extensibility options - for example, vastly speeding up reflection (without changing any code).

like image 20
Marc Gravell Avatar answered Oct 10 '22 15:10

Marc Gravell