Is there a way to add extra properties to an anonymous class (or create a new instance with the extra properties)?
string cssClasses = "hide";
object viewData = new { @class = cssClasses };
if (suppliedId != null)
{
// add an extra id property to the viewData somehow...
// desired end result is { @id = suppliedId, @class = cssClasses }
}
// ... code will be passing the viewData as the additionalViewData parameter in asp.mvc's .EditorFor method
No, you can't do it. You can redefine it, though:
dynamic viewData = new { @class = cssClasses };
if (suppliedId != null)
{
viewData = new { @class = viewData.@class, yourExtra = Property };
}
Note that I changed it to dynamic
. This is just so you can edit the properties without casting to dynamic
.
You can not add extra properties to anonymous types, but you can use two anonymous types.
If you don't like dynamic
(and there are reasons not to), you could do:
object viewData;
if (suppliedId == null)
viewData = new { @class = cssClasses, };
else
viewData = new { @id = suppliedId, @class = cssClasses, };
If you want to keep separate exactly typed references to each object instance, then use:
var viewDataSimple = new { @class = cssClasses, };
var viewDataExtra = new { @id = suppliedId, @class = cssClasses, };
object viewDataToUse;
if (suppliedId == null)
viewDataToUse = viewDataSimple;
else
viewDataToUse = viewDataExtra;
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With