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

How to use Expression to build an Anonymous Type?

You’re close, but you have to be aware that anonymous types don’t have default constructors. The following code prints { Name = def, Num = 456 }: Type anonType = new { Name = “abc”, Num = 123 }.GetType(); var exp = Expression.New( anonType.GetConstructor(new[] { typeof(string), typeof(int) }), Expression.Constant(“def”), Expression.Constant(456)); var lambda = LambdaExpression.Lambda(exp); object … Read more

IEqualityComparer for anonymous type

The trick is to create a comparer that only works on inferred types. For instance: public class Comparer<T> : IComparer<T> { private Func<T,T,int> _func; public Comparer(Func<T,T,int> func) { _func = func; } public int Compare(T x, T y ) { return _func(x,y); } } public static class Comparer { public static Comparer<T> Create<T>(Func<T,T,int> func){ return … Read more

C# 7.0 ValueTuples vs Anonymous Types

Anonymous types are immutable, ValueTuples are not. This is reflected in the fact that anonymous types expose properties, ValueTuples expose fields. Data binding almost always requires properties. Plenty of existing code only works with reference types, not with value types. What in particular comes to mind are projections in Entity Framework: projections to value types … Read more

Convert anonymous type to class

Well, you could use: var list = anBook.Select(x => new ClearBook { Code = x.Code, Book = x.Book}).ToList(); but no, there is no direct conversion support. Obviously you’ll need to add accessors, etc. (don’t make the fields public) – I’d guess: public int Code { get; set; } public string Book { get; set; } … Read more

Convert anonymous type to new C# 7 tuple type

Of course, by creating the tuple from your LINQ expression: public (int id, string name) GetSomeInfo() { var obj = Query<SomeType>() .Select(o => (o.Id,o.Name)) .First(); return obj; } According to another answer regarding pre-C# 7 tuples, you can use AsEnumerable() to prevent EF to mix things up. (I have not much experience with EF, but … Read more

tech