Search code examples
c#cachingdelegates

Which (if any) locally defined delegates are cached between method calls?


This was mentioned in my other question and I thought it might be useful to add it to the record. In the following program, which, if any, of the locally defined delegates are cached between calls to the Work method instead of being created from scratch each time?

namespace Example
{
    class Dummy
    {
        public int age;
    }

    class Program
    {
        private int field = 10;

        static void Main(string[] args)
        {
            var p = new Program();

            while (true)
            {
                p.Work();
            }
        }

        void Work()
        {
            int local = 20;

            Action a1 = () => Console.WriteLine(field);
            Action a2 = () => Console.WriteLine(local);
            Action a3 = () => Console.WriteLine(this.ToString());
            Action a4 = () => Console.WriteLine(default(int));
            Func<Dummy, Dummy, bool> dummyAgeMatch = (l, r) => l.age == r.age;

            a1.Invoke();
            a2.Invoke();
            a3.Invoke();
            a4.Invoke();
            dummyAgeMatch.Invoke(new Dummy() { age = 1 }, new Dummy(){ age = 2 });
        }
    }
}

Solution

  • Based on what Reflector shows, the last two (a4 and dummyAgeMatch) are cached by the MS C#3.0 compiler (in fields called "CS$<>9_CachedAnonymousMethodDelegate5" and "CS$<>9_CachedAnonymousMethodDelegate6" in my particular build).

    These ones can be cached, whereas obviously the others depend on captured variables.

    I don't believe the behaviour is mandated by the spec, but the Mono compiler behaves in much the same way (with different variable names).