Change property value of a C# Dynamic type

2k views Asked by At

Is there any way to change a dynamic type property value ? Code Example:

dynamic result = new { Status = "WARNING", Modified = false, Message = string.Empty };
result.Status = "OK";

Is that possible at all using C# ? Thanks

2

There are 2 answers

0
Mong Zhu On

No this is not possible. You will get a runtime error telling you that the property Status of the anonymous type is write protected or read-only.

For future use here is the online compiler proof:

The documentation says:

Anonymous types contain one or more public read-only properties.

You would need to recreate the object again using the values from the original one for the rest of the properties:

var result = new { Status = "WARNING", Modified = false, Message = string.Empty };
result = new { Status = "OK", Modified = result.Modified, Message = result.Message };
Console.WriteLine(result.Status);

Output:

OK

1
user8524786 On

Dynamic data type is added in c# 4.0. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.

Though, in most cases, dynamic data type behaves like an object.

In the abovementioned example: You've created an anonymous type variable which is like the class type but it can only include public read-only members so you can't change result.Status value in this case.

TO SOLVE THE PROBLEM :


I think you should use generic collection like dictionary The code may look like this:

var result = new Dictionary<string, object>() { {"Status", "Warning"}, {"Modified", false}, {"Message", string.empty} };

result ["Status"] = "Ok";