c# - Where is the instance of "IntConverter" stored? -


let's suppose have following program:

public class program {     private static dictionary<type, func<object, object>> converters = new dictionary<type, func<object[], object>>();      public static void main(string[] args)     {          registerimplementation(new intconverter());          int value = (int) dic[typeof(int)]("4");          console.writeline(value); //prints 4     }      private static registerimplementation<x>(iconverter<x> converter)     {          type type = typeof(x);          func<object, object> conversion = (obj) => converter.convert(obj);          if(dic.containskey(type))              dic[type] = conversion;          else              dic.add(type, conversion);     } }  public interface iconverter<x> {     x convert(object obj); }  public class intconverter : iconverter<int> {     public int convert(object obj)     {         return convert.toint32(obj);     } } 

i understand of code, part that's driving me mad registerimplementation method. in dictionary storing func<object, object> instance, , converter not stored anywhere, assuming lose local reference when out of method.

so how can call function in dictionary afterwards , use reference of intconverter? stored? inside func<object, object>?

firstly, it's worth being clear question doesn't involve expression trees @ - lambda expression being converted delegate.

now, lambda expression this:

(obj) => converter.convert(obj) 

that captures local variable, converter. in practice, means c# compiler have created new class, this:

private class unspeakablename<x> {     public iconverter<x> converter;      public object method(object obj)     {         return converter(obj);     } } 

then method converted into:

private static registerimplementation<x>(iconverter<x> converter) {      unspeakablename<x> tmp = new unspeakablename<x>();      tmp.converter = converter;       type type = typeof(x);      func<object, object> conversion = tmp.method;      if(dic.containskey(type))          dic[type] = conversion;      else          dic.add(type, conversion); } 

so target of delegate instance of new class, , that keeps converter alive.


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -