Skip to content

What's the purpose of StrongBox<T>? #47774

Answered by stephentoub
msedi asked this question in Q&A
Discussion options

You must be logged in to vote

It let's you "box" a value type to the heap but in a strongly-typed manner, e.g. instead of doing:

object box = 42;
... // some time later
int i = (int)box;

and then being able to pass around the weakly-typed box, you can do:

var box = new StrongBox<int>(42);
... // some time later
int i = box.Value;

and then pass around box and access its Value, which is strongly typed as int (via the generic T). Hence the name "strong box", i.e. "strongly-typed box". (It's not limited for use with value types, though.)

You can see example uses of it here:
https://source.dot.net/#System.Private.CoreLib/StrongBox.cs,bdbb335cbbdee41b,references

Some typical (advanced) use cases include:

  • Sharing an individ…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@msedi
Comment options

Answer selected by msedi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants