views:

608

answers:

2

A very simple ?: operator in C#, combined with a simple array and LINQ (to Objects) call to Reverse() is apparently enough to cause the exception "System.Security.VerificationException: Operation could destabilize the runtime." when run on an ASP.NET web site running with "High" trust (note that "Full" is the default)

Here is the code, plus the straightforward workaround that I came up with:

protected void Page_Load(object sender, EventArgs e) {
    Repro();
    //Workaround();
}

private IEnumerable<string> Repro() {
    bool test = true;
    string[] widgets = new string[0];
    return test ? widgets : widgets.Reverse();
}

private IEnumerable<string> Workaround() {
    bool test = true;
    string[] widgets = new string[0];
    if (test) {
     return widgets;
    } else {
     return widgets.Reverse();
    }
}

To set the trust level to "High", the following must be added to the web.config file:

<trust level="High" originUrl=""/>

The workaround is functionality equivalent to the problematic ?: operator that repros the problem. My guess from reading related posts is this is a C# compiler bug. Anyone know what's going on here?

+1  A: 

This line does not have the issue:

return test ? widgets.AsEnumerable() : widgets.Reverse();
John Fisher
A: 

I found that changing the order of the expression works around the issue as well:

private IEnumerable<string> Workaround() {
    bool test = true;
    string[] widgets = new string[0];
    return !test ? widgets.Reverse() : widgets;
}

Go figure!

Andrew Arnott