0

I have got the following method

public static void Method1(ref List<int> list)
{//code to update list}

Is it possible to create a method that takes this method as a parameter similar to (but instead of Action< List> it uses Action< ref List>)

 public static void Method2(Action<List<int>> otherMethod)
    {var newList = new List<int>(); otherMethod(newList)}

My main problem is that my method uses reference while Action> does not take references. Is this possible?

Frank Grech
  • 35
  • 1
  • 9

2 Answers2

2

Yes, but you can't use Action<>/Func<> for it, you have to build the delegate "manually":

// Your method
public static void Method1(ref List<int> list)
{
}

// The delegate
public delegate void Method1Delegate(ref List<int> list);

// A method that accepts the delegate and uses it
public static void Method2(Method1Delegate del)
{
    List<int> list = null;
    del(ref list);
}
xanatos
  • 109,618
  • 12
  • 197
  • 280
0
class App
{
     private readonly Dictionary<Type, object> delegateMap;

     void Add<T>(Action<SomeClass<T>> foo)
     {
         object tmp;
         if (!delegateMap.TryGetValue(typeof(T), out tmp))
         {
              tmp = new List<Action<SomeClass<T>>>();
              delegateMap[typeof(t)] = tmp;
         }
         List<Action<SomeClass<T>> list = (List<Action<SomeClass<T>>) tmp;
         list.Add(foo);
     }

     void InvokeActions<T>(SomeClass<T> item)
     {
         object tmp;
         if (delegateMap.TryGetValue(typeof(T), out tmp))
         {
             List<Action<SomeClass<T>> list = (List<Action<SomeClass<T>>) tmp;
             foreach (var action in list)
             {
                 action(item);
             }
         }
     }
}

Use Delegates.

Abhishek Dey
  • 1,601
  • 1
  • 15
  • 38