0

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?

2
  • 1
    You really shouldn't do this. Pass a tuple. Commented Feb 10, 2010 at 17:12
  • Or just define a struct. Commented Feb 10, 2010 at 17:15

3 Answers 3

6

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Well in C# 4.0 you can use dynamic and then you can cast it to what you wnat

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.