Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over object fields in C#

Foo is a class with a lot of string fields. I want to create a method Wizardify that performs an operation on many of the fields of the object. I could do it like this:

Foo Wizardify(Foo input)
{
    Foo result;
    result.field1 = Bar(input.field1);
    result.field2 = Bar(input.field2);
    result.field3 = Bar(input.field3);
    ...

This is some easily generated code, but I prefer not to waste fifty lines on this. Is there a way to go over selected fields of an object? Note that there are four or five fields I want to work on in a different way and they should be excluded from the iteration.

like image 467
Vlad Vivdovitch Avatar asked Sep 01 '11 14:09

Vlad Vivdovitch


2 Answers

try

foreach ( FieldInfo FI in input.GetType().GetFields () )
{
    FI.GetValue (input)
    FI.SetValue (input, someValue)
}

Though I would not recommend the reflection approach for known Types - it is slow and depending on your specific scenario could pose some permission issue at runtime...

like image 145
Yahia Avatar answered Oct 21 '22 04:10

Yahia


This is what I have - it gives me a list (names) of all properties in my classes, that later I can work on with Reflection or "Expression trees":

private static string xPrev = "";
        private static List<string> result;

        private static List<string> GetContentPropertiesInternal(Type t)
        {
            System.Reflection.PropertyInfo[] pi = t.GetProperties();

            foreach (System.Reflection.PropertyInfo p in pi)
            {
                string propertyName = string.Join(".", new string[] { xPrev, p.Name });

                if (!propertyName.Contains("Parent"))
                {
                    Type propertyType = p.PropertyType;

                    if (!propertyType.ToString().StartsWith("MyCms"))
                    {
                        result.Add(string.Join(".", new string[] { xPrev, p.Name }).TrimStart(new char[] { '.' }));
                    }
                    else
                    {
                        xPrev = string.Join(".", new string[] { xPrev, p.Name });
                        GetContentPropertiesInternal(propertyType);
                    }
                }
            }

            xPrev = "";

            return result;
        }

        public static List<string> GetContentProperties(object o)
        {
            result = new List<string>();
            xPrev = "";

            result = GetContentPropertiesInternal(o.GetType());

            return result;
        }

Usage: List<string> myProperties = GetContentProperties(myObject);

like image 32
Denis Avatar answered Oct 21 '22 04:10

Denis