Assign an anonymous delegate to an hashtable

M

Marco Segurini

Hi,

Building the following code


namespace DelegateAnonymousToMap
{
class Program
{
class MyClass { }

static void Main(string[] args)
{
System.Collections.Hashtable hash = new
System.Collections.Hashtable();
hash.Add(1, delegate() { return new MyClass(); });
}
}
}


I get:

C:\..\Program.cs(14,10): error CS1502: The best overloaded method match
for 'System.Collections.Hashtable.Add(object, object)' has some invalid
arguments
C:\..\Program.cs(14,22): error CS1503: Argument '2': cannot convert from
'anonymous method' to 'object'


How may I solve this problem using anonymous delegate?

TIA.
Marco.
 
M

Mattias Sjögren

Marco,
How may I solve this problem using anonymous delegate?

You have to specify the delegate type since it can't be inferred from
the parameter type. Something like

SomeDelegate d = delegate() { return new MyClass(); };
hash.Add(1, d);



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top