# Anonymous types — new { Name, Age }

> `new { Name = "Ada", Age = 36 }` is an anonymous type, as in C#: a value whose members you read by name (`p.Age`), in a function, a test, a UI action, a computed and the browser alike. Where a `Json` document is wanted — a `Json` column, parameter or return, a request body — the same object becomes that document.

<!-- id: json-anonymous-types · area: json · stability: stable · html: https://osysharp.com/reference/json/anonymous-types/ -->

## Summary        {#summary}
**`new { … }`** with no type name is an **anonymous type**, exactly as in C#. Its members are named where it is
written, and read by those names wherever the value goes:

```osy syntax
var p = new { Name = "Ada", Age = 36 };
var next = p.Age + 1;                    // 37 — `Age` is an int
```

The same object is also how a **JSON document** is written inline: given to a `Json` column, parameter, local or
return, or passed as a request body, it becomes that document ([#as-a-document](#as-a-document)).

## Signature      {#signature}
```osy syntax
new { Name = value, Other = value }    // members named where they are written
new { o.Name, count }                  // …or named by what they read: Name = o.Name, count = count
```

## Description    {#description}
### What is an anonymous object's type?     {#its-type}
A type made from its member **names and types**, in the order written. Nothing declares it and nothing needs to:
two anonymous objects with the same members, in the same order, are the same type — as C# says — so a list of them,
a `Select` that makes them, and a local that holds one all agree.

Each member is the type of its value: `Age = 36` is an `int`, `Price = 2.5m` a `decimal`, `Tags = tags` a
`List<string>`. A member's value may be a scalar, a class or entity value, or a list of either.

### Where can I read its members?     {#everywhere}
Everywhere it can be written. The same lines compile and give the same answer in a function, a `[Test]`, a UI
`action` and a `live var` computed — and in a page the action runs in the browser, with no call to the server:

```osy title="read an anonymous object's members in a page" test app=json-anonymous-types-page
using Osysharp.Ui;

[AllowAnonymous]
[Route("/")]
component Greeting() {
  live var person = new { Name = "Ada", Age = 36 };
  live var line = $"{person.Name} is {person.Age}";        // a computed reads the members
  string shown = "";
  action Next() {
    var p = new { person.Name, Age = person.Age + 1 };       // Name inferred from `person.Name`
    shown = $"{p.Name} turns {p.Age}";                        // runs in the browser
  }
  render {
    Stack() {
      Text(line);
      Text(shown);
      Button("Next year", onPress: Next);
    }
  }
}
```

It behaves as C#'s does: `p.ToString()` is `{ Name = Ada, Age = 36 }`, and `a.Equals(b)` compares member by member.

### Can a member's name be left out?     {#inferred-names}
Yes, when the value already names it: a member access gives its member's name and a bare local or parameter gives
its own. `new { o.Name, count }` is `new { Name = o.Name, count = count }`. A value with no name of its own — a call,
an index, a sum — needs one written (`Total = a + b`), as C# requires.

### How do I turn one into JSON?     {#serialize}
[JsonSerializer](https://osysharp.com/reference/json/serializer/) writes it as C# does — its members in the order written, a list as an array:

```osy title="serialize an anonymous object" test app=json-anonymous-types
string Body(string name, List<int> items) {
  return JsonSerializer.Serialize(new { Name = name, Items = items });   // {"Name":"Ada","Items":[1,2]}
}
```

That works in a page too: the action above could serialize `p` in the browser.

### When does it become a `Json` document?     {#as-a-document}
Wherever a [Json](https://osysharp.com/reference/types/json/) value is wanted, an anonymous object is converted to that document — a `Json` column or
member, a `Json` parameter, local or return, and the body of an [Http.*](https://osysharp.com/reference/http/facade/) request:

```osy title="an anonymous object written to a Json column" test app=json-anonymous-types
entity Job { [Required, MaxLength(50)] string Name; Json Detail; }

void Record(int attempt, string reason) {
  var detail = new { attempt = attempt, reason = reason };
  var j = new Job { Name = "retry", Detail = detail };         // stored as {"attempt":2,"reason":"…"}
}

Json Describe(string code) {
  return new { code = code, fatal = false };                   // a Json return
}
```

An element of a `List<Json>` or a value of a `Dictionary<string, Json>` is converted the same way, however it gets
there — `Add`, `Insert`, `AddRange`, the indexer, a collection initializer or literal, or a whole `Select(…).ToList()`
assigned to a `List<Json>`. That is how a request body with a list in it is built:

```osy title="anonymous objects added to a List<Json>" test app=json-anonymous-types
string Messages(List<string> lines) {
  List<Json> messages = [];
  messages.Add(new { role = "system", content = "Be brief." });
  foreach (var line in lines) { messages.Add(new { role = "user", content = line }); }
  return JsonSerializer.Serialize(new { model = "m-1", messages = messages });
  // {"model":"m-1","messages":[{"role":"system","content":"Be brief."},{"role":"user","content":"…"}]}
}
```

Once it is a `Json`, it is a document like any other: read it back through `JsonSerializer.Deserialize<T>`, not by
member.

### Can one anonymous object hold another?     {#nested}
Yes — and then the outer object is a **document** (a `Json` value), as it always was: `new { code = "E17", inner = new
{ retries = 3 } }` writes `{"code":"E17","inner":{"retries":3}}`, and a list of anonymous objects inside one is an
array of documents. Its members are not read by name; write a `class` when you need to read a nested shape back.

### What does the compiler refuse?     {#refusals}
| written | why |
|---|---|
| `new { a = 1, a = 2 }` | a member given twice |
| `new { ["a"] = 1 }` | the dictionary spelling — a member is a name |
| `new { Total() }` | a value with no name of its own: write `Total = Total()` |
| `int runs = new { a = 1 };` | an anonymous object is not an `int` |

## Examples       {#examples}
A list of anonymous objects, made by a `Select` and read by member:

```osy title="anonymous objects in a list" test app=json-anonymous-types
int LongNames(List<string> names) {
  var rows = names.Select(n => new { n, Len = n.Length }).ToList();
  return rows.Where(r => r.Len > 3).Count();
}
```

## See also       {#see-also}
- [JsonSerializer](https://osysharp.com/reference/json/serializer/) — `JsonSerializer.Serialize` writes an anonymous object as C# does
- [Json](https://osysharp.com/reference/types/json/) — the `Json` document an anonymous object becomes where one is wanted
- [Http.*](https://osysharp.com/reference/http/facade/) — an anonymous object as a request body
