3 ms·
Where do C# anonymous types fall? From a functional perspective, they are a purely structural type. Here's a snippet of C# I wrote recently to transform some
by CharlieDigital 3y ago
Where do C# anonymous types fall? From a functional perspective, they are a purely structural type.
Here's a snippet of C# I wrote recently to transform some JSON:
var transformed = media.Select(m => {
var parts = m.Split('/');
return new {
addedAtUtc = "2023-05-15T05:59:31.398Z",
originTripUid = parts[4],
path = $"{parts[4]}/{parts[5]}",
rank = "",
size = 103978,
stored = true,
type = "document",
};
})
File.WriteAllText(
Path.Combine(Environment.CurrentDirectory, "output.json"),
System.Text.Json.JsonSerializer.Serialize(transformed)
);
It would be easy to mistake this as JS at a quick glance.
- oaiey 3y agoAnonymous types are nominal types (like all others in .NET). They are just auto-generated and auto-named. Duck Typing at runtime is possible and to a degree checkable and compile-time.
- CharlieDigital 3y agoI get that; that's why I qualified it as a "functional perspective" because even though the underlying implementation is an auto-generated, auto-named type, the functional usage of it is a structural type (with limitations).
- AshleyGrant 3y agoThey aren't structural because the following doesn't work in C#, but would work (with tweaks to make it valid code) in a structurally typed language such as TypeScript: var transformed = media.Select(m => { var parts = m.Split('/'); return new { addedAtUtc = "2023-05-15T05:59:31.398Z", originTripUid = parts[4], path = $"{parts[4]}/{parts[5]}", rank = "", size = 103978, stored = true, type = "document", }; }).ToList(); transformed.AddRange(otherMedia.Select(m => { var parts = m.Split('/'); return new { addedAtUtc = "2023-05-15T05:59:31.398Z", originTripUid = parts[4], path = $"{parts[4]}/{parts[5]}", rank = "", size = 103978, stored = true, type = "document", documentType = parts[6] }; })); Adding "documentType" breaks in C# but would work in a structurally typed language as a structural type checker can see that the second result fulfills all of the necessary properties. Doing this in C# would require creating an interface and being explicit.
- littlecranky67 3y agoUnless you were using the (yet unimplemented) exact types in TS. https://github.com/Microsoft/TypeScript/issues/12936 https://github.com/Microsoft/TypeScript/issues/12936
- AshleyGrant 3y agoSure, but that would be opt-in if it were ever implemented. I think both styles of type system have their pros and cons. I have loved the cross-pollination between C# and TS with great ideas flowing in both directions.