Note that there are some explanatory texts on larger screens.

plurals
  1. POOperation could destabilize the runtime?
    text
    copied!<p>I'm having a little bit of trouble understanding what the problem is here. I have a bit of code that pulls records from a database using LINQ and puts them into an object which is cast into an interface. It looks a bit like this:</p> <pre><code>public IEnumerable&lt;ISomeObject&gt; query() { return from a in dc.SomeTable select new SomeObject { //Assign various members here } as ISomeObject; } </code></pre> <p>When I test this, I put the returned IEnumerable into a variable called results and run this line:</p> <pre><code>Assert.AreEqual(EXPECTED_COUNT, results.Count()); </code></pre> <p>When this is run, I get a System.Security.VerificationException: "Operation could destabilize the runtime."</p> <p>I found the solution <a href="http://devlicio.us/blogs/derik_whittaker/archive/2008/11/29/quot-operation-could-destabilize-the-runtime-quot-from-casting-from-concrete-to-interfaces-with-linq.aspx" rel="noreferrer">here</a>, which is this:</p> <pre><code>var results = from a in dc.SomeTable select new SomeObject { //Assign various members here } as ISomeTable; return results.OfType&lt;ISomeObject&gt;(); </code></pre> <p>This works, but I'm having trouble understanding what's happening here. Why did I get the exception in the first place and how did the lines of code above fix it? The MSDN documentation seems to suggest that this is an issue of type safety, but I'm not seeing where the previous code was type-unsafe.</p> <p><strong>UPDATE</strong> A little bit more information I found out. The first example works if I make the return type IQueryable. This sheds a little bit more light on <em>what</em> was going wrong, but I'm still confused about the <em>why</em>. Why didn't the compiler force me to cast the IEnumerable into an IQueryable?</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