how to add property to anonymous class?

mc 5,426 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 }??

Developer technologies ASP.NET ASP.NET Core
Developer technologies .NET Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    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 122.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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.