Tuesday, April 19, 2016

What is Box in F#?

The first time I had to use the box function in F# there was some confusion on our team what exactly was happening under the hood. Our situation came when we had set an HTTP parameter to required in our WebAPI controller.

The Problem - The variable was in Int, it was required, and if it was not provided our application was supposed to return an error code. When the parameter was not provided WebAPI would set the required parameter to null even though Int cannot be null. This was very confusing, and to make matters worse we were not able to make the required parameter a Nullable<Int> with WebAPI.

The Solution - Box is the solution! From our searching, by boxing the int we could check if it is null even though it's not nullable (confusing). But what does the box function do? According to MSDN, the box function in F# "boxes a strongly typed value". Ok... Thanks documentation.

That's not all very helpful, but with further digging in this MSDN article the answer is "Boxing is the process of converting a value type to the type object..." It goes on to say "it wraps the value inside a System.Object and stores it on the managed heap..."

So, boxing a value wraps the value type inside a System.Object and therefore we can check if the object is null. Then we have to unbox it back to an Int after the null check.

Now the next time you box you'll hopefully have a better idea of what's happening. Happy boxing everyone!


  1. I am confident you've got a great enthusiast following there.
    best web site designs

  2. The team’s creative suggestions, proactive involvement, and impeccable organization continue to encourage efficiency.
    logo designing services

  3. Their professionalism and communicativeness ensure a smooth process, and their high-quality resources produce good work.
    top branding companies

  4. The new website is user-friendly and has been well received by multiple target groups.
    logo designing services

  5. The team’s communication skills were lacking, and their ability to meet deadlines fell short. Costs were unreasonable given the end result.
    web design companies

  6. It feels awe-inspiring to read such informative and distinctive articles on your websites.
    UI UX design services

  7. UI UX design services
    I have got the superb information from these blogs finally.