Are instances of anonymous types serializable into a session?
Problem
I have a one time use object which is a composite of several objects and their properties. I w开发者_C百科ould like to store this anonymous type into session and pull it back out again.
Questions which need answering
Is this a bad idea? If so, is there is a better way? (without creating a serializable object and storing that in session)
Also wondering if this can be done?
it is a bad idea; anon types are a poor choice outside of a single location. There is something called "cast by example", but it is not good practice. The right approach is simply "write a simple class to represent that state". With auto-props that is trivial.
Dynamic is another viable option (that can talk to anon-types), but again: what are you tryig to save here? Write the POCO/DTO already... It doesn't even need to be Serializable in many cases (unless ou have an out-of-process state server; in which case it is more important to have a known DTO).
Anonymous types are intended to be used within a single method body. Anytime you start passing them between methods you are asking for a bit of pain. It's much simpler at that point to just go ahead and define a concrete type and use that instead.
If you want to find a flexible middle ground between anonymous types and a traditional POCO, a NameValueCollection might work well for you.
精彩评论