Skip to content

Commit

Permalink
Added IDisposable section
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Nov 12, 2022
1 parent 10a5788 commit ab1402a
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions docs/site/articles/known_limitations.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ The base of the `ValueStringBuilder` is a `ref struct`. With that, there are cer
* Therefore they can't be boxed to `ValueType` or `Object`.
* Can't be captured by a lambda expression (aka closure).
* Can't be used in `async` methods.
* Can't be used in methods that use the `yield`` keyword
* Can't be used in methods that use the `yield` keyword

If not off this applies to your use case, you are good to go. Using `ref struct` is a trade for performance and fewer allocations in contrast to its use cases.

Expand All @@ -25,4 +25,21 @@ var greeting = stringBuilder
.ToString();
```

This does not work with the `ValueStringBuilder`. The simple reason: `struct`s can't return `return ref this`. If we don't return the reference then new allocations are introduced and can also lead to potential bugs/issues. Therefore it is a conscious design decision not to allow fluent notation.
This does not work with the `ValueStringBuilder`. The simple reason: `struct`s can't return `ref this`. If we don't return the reference then new allocations are introduced and can also lead to potential bugs/issues. Therefore it is a conscious design decision not to allow fluent notation.

## IDisposable
The `ValueStringBuilder` does not directly implement `IDisposable` as `ref struct`s are not allowed to do so (as they might get boxed in the process, which violates the rule of `ref struct`s). Still, the `using` statement can be used with the `ValueStringBuilder`. It is used to return rented memory from an array pool if any is taken.

```csharp
using var stringBuilder = new ValueStringBuilder();
```

There are scenarios, where you can elide the `using` keyword. Exactly then when you provide the buffer in the first place and you are **sure** that no internal growing has to be done. This should only be done if you can guarantee that.

```csharp
// Reserve 128 bytes on the stack and don't use the using statement
var stringBuilder = new ValueStringBuilder(stackalloc char[128]);

stringBuilder.Append("Hello World"); // Uses 11 bytes
return stringBuilder.ToString();
```

0 comments on commit ab1402a

Please sign in to comment.