class __Anonymous1 { private T1 f1 ; private T2 f2 ; // … private Tn fn ; public T1 p1 { get { return f1 ; } set { f1 = value ; } } public T2 p2 { get { return f2 ; } set { f2 = value ; } } // … public Tn pn { get { return fn ; } set { fn = value ; } } }
var myValue = new { A = 2, B = 3 };
class A<T> where T : new() { void B() { var myValue = new { C = new T() }; } } // Turns into: class A<T> where T : new() { // Note the use of a value type for a small type struct __Anonymous1 { private T c; public T C { get { return c; } set { c = value; } } } void B() { __Anonymous1 myValue = new __Anonymous1(); myValue.C = new T(); } }
Properties are used for serilization purposes I believe. Public fields are not serialized.
>Properties are used for serilization purposes I
>believe. Public fields are not serialized.
this is the glib answer i thought of too ;-)
any response? is serialization still useful with anonymous types?
are these types not likely to be persisted or transmitted (hence serialization is less important)?
Alex / Leon - When a SerializableAttribute is placed on a type, all fields not marked as NotSerialized are used for the type's serialization. Properties are used for binding and maybe that's what threw you off.
Serialization is only useful when you're persisting/reading an object grid to a stream. Since the original intention was for anonymous types to be contained in a single scope, there's no reason to ever serialize them.
Since the type's name/structure isn't deterministic, you can't expect to be able to read it from a stream after having it written somewhere else with zero problems.
As for binding - I don't see why anyone would want to go through that nightmare.
I'm thinking future extensibility -- what if I could have an anonymous type that performed some anonymous behavior for each of it's properties? perhaps an OnPropertyChanged() similar to rails... it would be somewhat breaking to change the fields to properties...??
"As for binding - I don't see why anyone would want to go through that nightmare."
But people still use untyped datasets *shrug*
Good points.
I've come to the conclusion that it might be useful to mark anonymous types as serializable.
For example, I was recently trying to reduce the amount of plumbing needed to run a snippet of code in another AppDomain. I turned to anonymous methods and generic classes, and ran into the issue that anonymous types are not marked as serializable and thus can't cross the AppDomain boundaries. Check out this post for some example code that fails.
http://thevalerios.net/matt/2008/06/run-anonymous-methods-in-another-appdomain/
So, how about this:
If any anonymous type is created where ALL of the member property types are marked as Serializable, then also mark the anonymous type’s class as Serializable.