Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to initialize a struct in array with readonly values using Expression Trees in C#
    text
    copied!<p>I need to generate code using Expression trees that quickly fills out an array of structs <code>T[]</code> where T contains a readonly field. I need to initialize it like after GetUninitializedObject() + IL or reflection-based setters.</p> <p><strong>UPDATE: At the moment it appears to be impossible. Please <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2727812-allow-expression-assign-to-set-readonly-struct-f" rel="nofollow">vote for it at MS Suggestions</a></strong></p> <pre><code>struct Strct { public readonly int Value; } </code></pre> <p>this code fails:</p> <pre><code>Expression.Assign( Expression.Field(structByIndexFromArrayExp, "Value"), deserializedValueExp) </code></pre> <p>During the expression tree construction, I get this error: <code>Expression must be writeable</code> Which totally makes sense from the regular code perspective, but not during deserialization.</p> <p><code>FormatterServices.GetUninitializedObject()</code> returns an object, which I would guess I need to avoid as it is boxed and therefore significantly slower.</p> <p>What is the quickest way to initialize such struct arrays?</p> <p><strong>Update:</strong> At the moment the only realistic way I see is to dynamically generate a clone of struct T but without readonly attribute on fields, fill them out, fix both arrays in memory and do a memory copying. <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2727812-allow-expression-assign-to-set-readonly-struct-f" rel="nofollow">Please vote to tell Microsoft to fix it</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload