0

Is there a possibility to name an anonymous method while still inside it? I need to do this to store the method inside a dictionary (myDict<Type, List<Action<object>>>) and then need to remove it later on. For removing I need a reference e.g. a name since each key can point to a List. Would there be a better way of storing and removing anonymous methods inside a collection?

schwarz
  • 501
  • 7
  • 28

2 Answers2

0

I don't think you can do what you want. Two different anonymous delegates are not guaranteed to be equal even if they are defined by the identical c# code. From the c# specification:

Every delegate type implicitly provides the following predefined comparison operators:

bool operator ==(System.Delegate x, System.Delegate y);

bool operator !=(System.Delegate x, System.Delegate y);

Two delegate instances are considered equal as follows:

• If either of the delegate instances is null, they are equal if and only if both are null.

• If the delegates have different run-time type they are never equal.

• If both of the delegate instances have an invocation list (§15.1), those instances are equal if and only if their invocation lists are the same length, and each entry in one’s invocation list is equal (as defined below) to the corresponding entry, in order, in the other’s invocation list.

The following rules govern the equality of invocation list entries:

• If two invocation list entries both refer to the same static method then the entries are equal.

• If two invocation list entries both refer to the same non-static method on the same target object (as defined by the reference equality operators) then the entries are equal.

• Invocation list entries produced from evaluation of semantically identical anonymous-function-expressions with the same (possibly empty) set of captured outer variable instances are permitted (but not required) to be equal.

You may need to name your methods, as is shown here.

Also, consider using a dictionary of event instances rather than a custom-built dictionary of lists of actions. Microsoft gives an example of this here: How to: Use a Dictionary to Store Event Instances (C# Programming Guide).

Community
  • 1
  • 1
dbc
  • 104,963
  • 20
  • 228
  • 340
0

This would be a way(but not inside the method):

Action<object> first = delegate (object f){ Console.WriteLine(f + "first");};
Action<object> second = delegate(object s) { Console.WriteLine(s + "second"); };
Action<object> third = delegate(object t) { Console.WriteLine(t + "third"); };

Dictionary<Type, List<Action<object>>> myDict = new Dictionary<Type, List<Action<object>>>();

myDict.Add(typeof(Bar), new List<Action<object>>());
myDict[typeof(Bar)].AddRange(new[] { first, second, third });

myDict[typeof(Bar)].Remove(first);

I placed anonymous methods since you did not especify lambdas.

terrybozzio
  • 4,424
  • 1
  • 19
  • 25