Return/consume dynamic anonymous type across assembly boundaries

Use an ExpandoObject instead of an anonymous type. This should allow you to cross assembly boundaries safely: public static dynamic GetPerson() { dynamic person = new ExpandoObject(); person.Name = “Foo”; person.Age = 30; return person; } In general, anonymous types should really only be used within the same method in which they are generated. Returning … Read more

How To Test if a Type is Anonymous? [duplicate]

From http://www.liensberger.it/web/blog/?p=191: private static bool CheckIfAnonymousType(Type type) { if (type == null) throw new ArgumentNullException(“type”); // HACK: The only way to detect anonymous types right now. return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false) && type.IsGenericType && type.Name.Contains(“AnonymousType”) && (type.Name.StartsWith(“<>”) || type.Name.StartsWith(“VB$”)) && type.Attributes.HasFlag(TypeAttributes.NotPublic); } EDIT: Another link with extension method: Determining whether a Type is an Anonymous Type

Anonymous Types – Are there any distingushing characteristics?

EDIT: The list below applies to C# anonymous types. VB.NET has different rules – in particular, it can generate mutable anonymous types (and does by default). Jared has pointed out in the comment that the naming style is different, too. Basically this is all pretty fragile… You can’t identify it in a generic constraint, but: … Read more

Convert Dictionary To Anonymous Object?

If you really want to convert the dictionary to an object that has the items of the dictionary as properties, you can use ExpandoObject: var dict = new Dictionary<string, object> { { “Property”, “foo” } }; var eo = new ExpandoObject(); var eoColl = (ICollection<KeyValuePair<string, object>>)eo; foreach (var kvp in dict) { eoColl.Add(kvp); } dynamic … Read more

How should anonymous types be used in C#?

Anonymous types have nothing to do with the design of systems or even at the class level. They’re a tool for developers to use when coding. I don’t even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would … Read more