F# equivalent of C#’s Object Initialization syntax

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

Step Functions, EventBridge, MSK, DynamoDB…stop hacking together AWS services and get back to building!

See how it works

In C#, you can use the object/collection initialization syntax like this:

image

The F# equivalent of object initialization is done like this:

image

As for collection initialization, you have a far more diverse range of tools available to you, for example:

image

You can also create slices of an existing array:

image

You can even add your own multi-dimensional indexers to support similar behaviours in your type too!

Update 2012/01/11:

As Robert Pickering mentioned in the comments, slicing is not limited to arrays, it works with other collection types too (as long as a GetSlice extension method is defined on the type, for more information, see here). For instance, you can use slicing on a string like this:

image

With 2D arrays, you can also use a multi-dimensional slicer too:

image

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

3 thoughts on “F# equivalent of C#’s Object Initialization syntax”

  1. Sebastian Ullrich

    Collection initializer != array initializer. There’s no F# equivalent of C#’s collection initializers.

  2. Sebastian Ullrich: you’re not limited to using array initialization in F#, it works with arrays, lists and sequences (which is a F# alias for IEnumerable).

Leave a Comment

Your email address will not be published. Required fields are marked *