how to add property to anonymous class?

mc 4,111 Reputation points

how to add class to dynamic/anonymous class?

I have object Value I do not know what class it is and can add property to it?

object is { Status = 1 ,Value ="x" }

can become? {Status =1 ,Value="x", Code=-1 }??

Microsoft Technologies based on the .NET software framework.
3,622 questions
A set of technologies in the .NET Framework for building web applications and XML web services.
4,381 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,091 Reputation points Microsoft Vendor

    Hi @mc

    You can try to create a ExpandoObject to add the property. Check the following code:

            public IActionResult Get()
                var data = new { Status = 1, Value = "x" };
                //define a dictionary to store the property and the value.
                Dictionary<string, object> dic = new Dictionary<string, object>();
                //find original property from the anonymous class.
                foreach (var pro in data.GetType().GetProperties())
                    dic.Add(pro.Name, pro.GetValue(data, null).ToString());
                //create a ExpandoObject
                var eo = new ExpandoObject();
                var eoColl = (ICollection<KeyValuePair<string, object>>)eo;
                //add the property and value into the expandoObject.
                foreach (var kvp in dic)
                //add new property.
                eoColl.Add(new KeyValuePair<string, object>("Code", "111"));
                dynamic result = eoColl;
                var testdata = result.Code;
                return Ok(result);

    The result as below:


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,


    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 114.5K Reputation points

    For example, new { t.Status, t.Value, Code = -1 }, where t is your object.