views:

146

answers:

2

Consider a scenario where a block of code is trying to pass an anonymous object to another method in C#.

Here's an example:

ThreadPool.QueueUserWorkItem(new WaitCallback(RpvService.GetRpvDailyResults),
                             new { req = request, rpvDic = rpvDictionary }
                            );

How can you receive the anonymous object at the receiving end?

+5  A: 

It would be much better to just define your own class or struct.

An anonymous object is nothing but a class the compiler generates for you. It's a bad idea to try to pass this between methods, since it's going to cause problems.

There is no disadvantage to defining the type yourself. Since there are only two objects, you could also use KeyValuePair (.NET 2) or Tuple (in .NET 4).

Reed Copsey
+2  A: 

From MSDN:

An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Colin Desmond