In C#, you can use the object/collection ini­tial­iza­tion syn­tax like this:

image

The F# equiv­a­lent of object ini­tial­iza­tion is done like this:

image

As for col­lec­tion ini­tial­iza­tion, you have a far more diverse range of tools avail­able to you, for example:

image

You can also cre­ate slices of an exist­ing array:

image

You can even add your own multi-dimensional index­ers to sup­port sim­i­lar behav­iours in your type too!

Update 2012/01/11:

As Robert Pick­er­ing men­tioned in the com­ments, slic­ing is not lim­ited to arrays, it works with other col­lec­tion types too (as long as a Get­Slice exten­sion method is defined on the type, for more infor­ma­tion, see here). For instance, you can use slic­ing on a string like this:

image

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

image

Share

3 Responses to “F# equivalent of C#’s Object Initialization syntax”

  1. Nice arti­cle. Prob­a­bly worth men­tion­ing that array slic­ing can also be used with strings and most other types of collections.

  2. Sebastian Ullrich says:

    Col­lec­tion ini­tial­izer != array ini­tial­izer. There’s no F# equiv­a­lent of C#‘s col­lec­tion initializers.

  3. theburningmonk says:

    Sebas­t­ian Ull­rich: you’re not lim­ited to using array ini­tial­iza­tion in F#, it works with arrays, lists and sequences (which is a F# alias for IEnumerable).

Leave a Reply