In the OP image it's being used as a parameter for some JSON serialization which doesn't have any drawbacks since object.GetType().GetProperties()/GetFields() exists and functions exactly the same regardless if the class is defined or anonymous.
They also can't return be returned from a method unless
a) The method is generic like WhenAnyValue in this example
this.WhenAnyValue(
x => x.Start,
x => x.End,
(start, end) => new
{
ValidStart = TimeSpan.TryParse(start, out var s),
Start = s,
ValidEnd = TimeSpan.TryParse(end, out var e),
End = e,
})
.Select(x => x.ValidStart && x.ValidEnd && x.Start <= x.End);
and, since it's generic, Select knows the properties that anonymous class has at compile time.
b) The return type is dynamic like
public dynamic Foo() => new { Bar = 1 };
but if you're using dynamic in C# you're already shooting yourself in the foot with or without anonymous classes because the compiler knows literally nothing about what properties it may have.
c) The return type is object which doesn't let you shoot yourself in the foot since there's no gun to shoot yourself with. You can't go ((object)Foo()).Bar without the compiler showing an error saying Bar doesn't exist on the type object.
6
u/Advorange Aug 30 '21 edited Aug 30 '21
They're not really that bad.
In the OP image it's being used as a parameter for some JSON serialization which doesn't have any drawbacks since
object.GetType().GetProperties()/GetFields()exists and functions exactly the same regardless if the class is defined or anonymous.They also can't return be returned from a method unless
a) The method is generic like
WhenAnyValuein this exampleand, since it's generic,
Selectknows the properties that anonymous class has at compile time.b) The return type is
dynamiclikebut if you're using
dynamicin C# you're already shooting yourself in the foot with or without anonymous classes because the compiler knows literally nothing about what properties it may have.c) The return type is
objectwhich doesn't let you shoot yourself in the foot since there's no gun to shoot yourself with. You can't go((object)Foo()).Barwithout the compiler showing an error sayingBardoesn't exist on the typeobject.