TypeLoadException not caught by try / catch method

I'm trying to recreate TypeLoadExceptionfor demo purposes, so I have a ridiculously dumb library set that looks like this:

TestProject --> TheLibrary [1.0]
            \-> ProxyForV2 -> TheLibrary [2.0]

TheLibrary version 1 has the following interfaces:

public interface IConsistentThing
{
    int ConsistentProperty { get; set; }
}

public interface IShrinkingThing
{
    int RemovedProperty { get; set; }
}

While version 2 of the interfaces TheLibrarylooks like this:

public interface IConsistentThing
{
    int ConsistentProperty { get; set; }
}

public interface IShrinkingThing
{ }

ProxyForV2has this class that implements version 2.0 IShrinkingThing:

public class ShrinkingThingImpl : IShrinkingThing
{
    public int ConsistentProperty { get; set; }
}

So, in TestProjectI expect to call TypeLoadExceptionif someone tries to assign ProxyForV2.ShrinkingThingImpl, since the first version of the interface has a property that is not implemented by the second version. To prove this, I have a unit test that looks like this:

[TestMethod]
public void ShrinkingThingBreaks()
{
    try
    {
        IShrinkingThing thing = new ProxyForV2.ShrinkingThingImpl();

        Assert.Fail("This should have caused a TypeLoadException");
    }
    catch (TypeLoadException)
    {
        //  valid
    }
}

Here is my problem: this unit test fails. But not because of mine Assert.Fail, as I would expect it. The test result is as follows:

TestProject.LoadTester.ShrinkingThingBreaks : System.TypeLoadException: get_RemovedProperty "ProxyForV2.ShrinkingThingImpl" "ProxyForV2, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null" .

, TypeLoadException, , , try catch (TypeLoadException), . , catch-all, unit test , :

[TestMethod]
public void ShrinkingThingBreaks()
{
    try
    {
        IShrinkingThing thing = new ProxyForV2.ShrinkingThingImpl();

        Assert.Fail("This should have caused a TypeLoadException");
    }
    catch
    {
        //  valid
    }
}

? , , , , , , , (, , , ).

, , typeof(ProxyForV2.ConsistentThingImpl) ProxyForV2.ConsistentThingImpl.SomeStaticFunction() TypeLoadException, , , .NET , - .

- , , , , , .

: "" ?

+3
1

, . :

[TestMethod]
public void ShrinkingThingBreaks()
{
    try
    {
        InnerShrinkingThingBreaks();

        Assert.Fail("This should have caused a TypeLoadException");
    }
    catch
    {
        //  valid
    }
}

[MethodImpl(MethodImplAttributes.NoInlining)]
private void InnerShrinkingThingBreaks()
{
        IShrinkingThing thing = new ProxyForV2.ShrinkingThingImpl();
}
+6

Source: https://habr.com/ru/post/1756792/


All Articles