how to add property to anonymous class?

mc 4,111 Reputation points
2023-05-23T16:13:03.77+00:00

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 }??

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,622 questions
ASP.NET Core
ASP.NET Core
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
    2023-05-25T08:58:04.9766667+00:00

    Hi @mc

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

            [HttpGet]
            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)
                {
                    eoColl.Add(kvp);
                }
                //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:

    image2


    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,

    Dillion

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 114.5K Reputation points
    2023-05-23T16:46:27.3+00:00

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