Different behavior of reflected generic delegates with and without debugger

Posted by Andrew_B on Stack Overflow See other posts from Stack Overflow or by Andrew_B
Published on 2010-05-17T09:28:51Z Indexed on 2010/05/17 11:30 UTC
Read the original article Hit count: 187

Filed under:
|
|
|

Hello. We have encountered some strange things while calling reflected generic delegates. In some cases with attatched debuger we can make impossible call, while without debugger we cannot catch any exception and application fastfails.

Here is the code:

using System;
using System.Windows.Forms;
using System.Reflection;

namespace GenericDelegate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private delegate Class2 Delegate1();

        private void button1_Click(object sender, EventArgs e)
        {
            MethodInfo mi = typeof (Class1<>).GetMethod("GetClass", BindingFlags.NonPublic | BindingFlags.Static);
            if (mi != null)
            {
                Delegate1 del = (Delegate1) Delegate.CreateDelegate(typeof (Delegate1), mi);
                MessageBox.Show("1");
                try
                {
                    del();
                }
                catch (Exception)
                {
                    MessageBox.Show("No, I can`t catch it");
                }
                MessageBox.Show("2");
                mi.Invoke(null, new object[] {});//It's Ok, we'll get exception here
                MessageBox.Show("3");
            }
        }


        class Class2
        {

        }


        class Class1<T> : Class2
        {
            internal static Class2 GetClass()
            {
                Type type = typeof(T);
                MessageBox.Show("Type name " + type.FullName +" Type: " + type + " Assembly " + type.Assembly);
                return new Class1<T>();
            }
        }
    }
}

There are two problems:

  1. Behavior differs with debugger and without
  2. You cannot catch this error without debugger by clr tricks. It's just not the clr exception. There are memory acces vialation, reading zero pointer inside of internal code.

Use case: You develop something like plugins system for your app. You read external assembly, find suitable method in some type, and execute it. And we just forgot about that we need to check up is the type generic or not. Under VS (and .net from 2.0 to 4.0) everything works fine. Called function does not uses static context of generic type and type parameters. But without VS application fails with no sound. We even cannot identify call stack attaching debuger.

Tested with .net 4.0

The question is why VS catches but runtime do not?

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection