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
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
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";
No this is not possible. You will get a runtime error telling you that the property
Statusof the anonymous type is write protected or read-only.For future use here is the online compiler proof:
The documentation says:
You would need to recreate the object again using the values from the original one for the rest of the properties:
Output: