Wednesday, January 11, 2012

Assigning null to anonymouse type properties

Just a quick note about handling an issue for anonymous types, if you wanted to assign a null value to a property you will face a compile error which says Cannot assign <null> to anonymous type property, and the easy solution for this is to write to cast the null to desired type, this is important specially if you are creating an array of anonymouse typed objects.

Here is a sample code:

return new[] { 
    new { Name = "Fixed Value", ViewModel = (objectnew B_FixedValue_EditViewModel() } ,
    new { Name = "Fixed List", ViewModel =  null as object} ,
    new { Name = "Calculation on one value", ViewModel = null as object } ,
    new { Name = "Calculation on two values", ViewModel = null as object } ,
    new { Name = "Loading a value from database", ViewModel = null as object } ,
    new { Name = "Conditional Value Provision", ViewModel = null as object} ,
};

1 comment: