Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate on all properties of an object in C#?

Tags:

c#

reflection

I am new to C#, I want to write a function to iterate over properties of an object and set all null strings to "". I have heard that it is possible using something called "Reflection" but I don't know how.

Thanks

like image 498
Ristovak Avatar asked Nov 27 '10 09:11

Ristovak


3 Answers

public class Foo
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public int Prop3 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo();

        // Use reflection to get all string properties 
        // that have getters and setters
        var properties = from p in typeof(Foo).GetProperties()
                         where p.PropertyType == typeof(string) &&
                               p.CanRead &&
                               p.CanWrite
                         select p;

        foreach (var property in properties)
        {
            var value = (string)property.GetValue(foo, null);
            if (value == null)
            {
                property.SetValue(foo, string.Empty, null);
            }
        }

        // at this stage foo should no longer have null string properties
    }
}
like image 154
Darin Dimitrov Avatar answered Nov 12 '22 23:11

Darin Dimitrov


foreach(PropertyInfo pi in myobject.GetType().GetProperties(BindingFlags.Public))
{
    if (pi.GetValue(myobject)==null)
    {
        // do something
    }
}
like image 22
Aliostad Avatar answered Nov 13 '22 00:11

Aliostad


object myObject;

PropertyInfo[] properties = myObject.GetType().GetProperties(BindingFlags.Instance);

See http://msdn.microsoft.com/en-us/library/aa332493(VS.71).aspx

like image 1
KBoek Avatar answered Nov 13 '22 00:11

KBoek