Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Any chance to cast this to the anonymous type?</p> </blockquote> <p>Although you can do that but it is highly unreliable. Because whenever you will change your creation of anonymous type your code will suddenly break on other places without a trace.</p> <p>You can read all the downfalls of casting anonymous types in blog by Jon Skeet <a href="https://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx" rel="nofollow">here</a>. Also worth reading are the comments by Marc Gravel. </p> <p><strong>Example</strong> of breaking change as discussed in the above blog.</p> <pre><code>using System; static class GrottyHacks { internal static T Cast&lt;T&gt;(object target, T example) { return (T) target; } } class CheesecakeFactory { static object CreateCheesecake() { return new { Fruit="Strawberry", Topping="Chocolate" }; } static void Main() { object weaklyTyped = CreateCheesecake(); var stronglyTyped = GrottyHacks.Cast(weaklyTyped, new { Fruit="", Topping="" }); Console.WriteLine("Cheesecake: {0} ({1})", stronglyTyped.Fruit, stronglyTyped.Topping); } } </code></pre> <p>All good. Now what if you suddenly realise that you need to change CreateCheeseCake to something like this</p> <pre><code>static object CreateCheesecake() { return new { Fruit="Strawberry", Topping="Chocolate", Base = "Biscuit" }; } </code></pre> <p>Then what will happen to your this line</p> <pre><code>var stronglyTyped = GrottyHacks.Cast(weaklyTyped, new { Fruit="", Topping="" }); </code></pre> <p>it won't work anymore.</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