> For the complete documentation index, see [llms.txt](https://andreyakinshin.gitbook.io/problembookdotnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://andreyakinshin.gitbook.io/problembookdotnet/ru/valuetypes/boxing-s.md).

# «Boxing» (Решение)

## Ответ

```
Foo
Foo
Foo
Bar
Baz
Foo
```

## Объяснение

Ключевым моментом в понимании примера является тот факт, что при вызове `Console.WriteLine` используется перегруженный вариант метода, принимающий аргумент типа `object`. Поэтому передаваемая в него структура упаковывается. Это означает, что в управляемой куче создаётся копия структуры, метод `ToString()` отрабатывает для упакованной копии. Теперь разберём пример по строчкам:

```csharp
var foo = new Foo();
Console.WriteLine(foo); // Displays "Foo" (value == 0)
Console.WriteLine(foo); // Displays "Foo" (value == 0)
```

Мы создали экземпляр структуры `Foo` и дважды выполнили для него `Console.WriteLine(foo)`. Дважды выполнилась копирование и упаковка структуры, `ToString()` вызвалось для копии, не тронув оригинал. Изначально `Foo.value == 0`, так что в обоих случаях выведется `"Foo"`.

```csharp
object bar = foo;
object qux = foo;
object baz = bar;
```

Тут мы явно выполняем упаковку структуры. Объекты `bar` и `qux` указывают на разные копии структуры, т.к. мы выполнили две отдельных операции упаковки. Объект `baz` указывает на ту же копию структуры, что и `bar`, т.к. в третьей строчке мы просто выполнили копирование ссылки.

```csharp
Console.WriteLine(baz); // Displays "Foo" (value == 0)
Console.WriteLine(bar); // Displays "Bar" (value == 1)
Console.WriteLine(baz); // Displays "Baz" (value == 2)
```

В этих трёх строчках мы работаем с одной и той же копией структуры, обращаясь к ней по ссылке (`bar` и `baz` представляют собой одну и ту же ссылку).

```csharp
Console.WriteLine(qux); // Displays "Foo" (value == 0)
```

А в этой строчке мы работаем с копией структуры, для которой метод `ToString()` ещё ни разу не вызывался. Поэтому выведется `"Foo"`.

[Задача](/problembookdotnet/ru/valuetypes/boxing-p.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://andreyakinshin.gitbook.io/problembookdotnet/ru/valuetypes/boxing-s.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
