Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to set property values with .NET

Tags:

c#

I have hundreds of properties that need to be set in an object, which is hierarchical by nature and would like a generic way of doing so, is this feasible? One of the driving reasons is for error checking and logging.

In this sample below I am setting ReferenceModelIdentifier to a string

    public override void Execute(MESSAGE message)
    {
        message.MISMOReferenceModelIdentifier= "3.0.0.263.12";

        Tasks.Add(new AboutVersionsTask(LoanNumber, LoanState));
        Tasks.Add(new DealSetsTask(LoanNumber, LoanState));

        foreach (var task in Tasks)
            using (task)
                task.Execute(message);

        // Were the tasks successful?
        Debug.Assert(message.ABOUT_VERSIONS.ABOUT_VERSION.Count > 0, "ABOUT_VERSION");
        Debug.Assert(message.DEAL_SETS.DEAL_SET.Count > 0, "DEAL_SET");

        Log.Info("Finished Execute");
    }

and in this sample I am setting ApplicationReceivedDate to another object of type MISMODate

    public override void Execute(MESSAGE message)
    {
        var node = new LOAN_DETAIL();

        var con = GetOpenConnection();
        string sql;
        IEnumerable<dynamic> data;
        dynamic first;

        if (LoanState == LoanStateEnum.AtClosing)
        {
            //(224) ApplicationReceivedDate
            sql = @"
                SELECT date ApplicationReceivedDate 
                FROM   foo (nolock) 
                WHERE  loannum = @loannum";

            data = con.Query<dynamic>(sql, new { loannum = new DbString { Value = LoanNumber, IsFixedLength = true, Length = 15, IsAnsi = true } });

            first = data.First();
            node.ApplicationReceivedDate = new MISMODate { TypedValue = first.ApplicationReceivedDate.ToString("yyyy-MM-dd") };
        }
    }

What I started out coding was something along the lines of

    protected void SetValue(Object property, Object value)
    {

    }

and the usage would be

    SetValue(message.MISMOReferenceModelIdentifier, "3.0.0.263.12");

EDIT

What I ended up doing was this

    protected void SetValue(object theObject, string theProperty, object theValue)
    {
        try
        {
            var msgInfo = theObject.GetType().GetProperty(theProperty);
            msgInfo.SetValue(theObject, theValue, null);

        }
        catch (Exception e)
        {
           Log(e);
        }
    }

and usage would be

SetValue(message, "MISMOReferenceModelIdentifier", "3.0.0.263.12");

Thank you, Stephen

like image 695
Stephen Patten Avatar asked Sep 13 '11 16:09

Stephen Patten


2 Answers

You can iterate over your object graph and set property values with reflection:

object obj; // your object

Type t = obj.GetType();
foreach (var propInfo in t.GetProperties())
{
    propInfo.SetValue(obj, value, null);
}

If you can ensure that your class properties have getters you can iterate your object graph recursive:

public static void setValsRecursive(object obj, object value)
{
    Type t = obj.GetType();
    foreach (var propInfo in t.GetProperties())
    {
        if (propInfo.PropertyType.IsClass)
        {
            object propVal = propInfo.GetValue(obj, null);
            setValsRecursive(propVal, value);
        }
        propInfo.SetValue(obj, value, null);
    }
}   

This is a dumb function that sets every property to the same value ...

like image 99
Jan Avatar answered Sep 25 '22 18:09

Jan


You can use PropertyInfo to dynamically set values in a generic way.

like image 27
Mark Cidade Avatar answered Sep 23 '22 18:09

Mark Cidade