Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra properties to an anonymous class

Tags:

c#

asp.net-mvc

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
like image 281
Jonathan Moffatt Avatar asked Jul 23 '13 07:07

Jonathan Moffatt


2 Answers

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.

like image 85
It'sNotALie. Avatar answered Sep 21 '22 14:09

It'sNotALie.


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.

like image 29
Jeppe Stig Nielsen Avatar answered Sep 21 '22 14:09

Jeppe Stig Nielsen