views:

303

answers:

3

How can you write the following F# code (or similar) in one line:

let contextMenu = new ContextMenuStrip()
mainForm.ContextMenuStrip <- contextMenu

I have to declare contextMenu as it will be needed later.

Thank you

+4  A: 

I don't recommand you to write it on a single line because this means it will be a mix between the #light (the mode by default now) and non #light syntax. If you really need to, you can use ;; like that:

open System
open System.Windows.Forms

let mainForm = new Form()
let contextMenu = new ContextMenuStrip();; mainForm.ContextMenuStrip <- contextMenu;;

If your expressions have unit type you can use a Sequential Execution Expression, which is an expression of the form:

expr1; expr2; expr3

for instance:

mainForm.ContextMenuStrip <- contextMenu; 5 + 6 |> ignore; mainForm.ContextMenuStrip <- null

I'd like to add that Sequential Execution Expressions have nothing to do with the non #light mode. They are just a general language construct.

Hope it helps.

Stringer Bell
+3  A: 

You can set public, writeable properties as pseudo-parameters in the constructor.

let contextMenu = new ContextMenuStrip()
let form = new Form(ContextMenuStrip = contextMenu)
Chris Smith
Why was this voted down?
RodYan
+1, My guess is that there could be a side effect in the property setter and it scared someone. I like this syntax. It encourages people to write small constructors and use properties instead.
gradbot
Oh I see, he's setting the value in the Form not the ContextMenuStrip. So it doesn't answer the question though I still found this answer of use.let contextMenu = new ContextMenuStrip()let mainForm = new Form(ContextMenuStrip = contextMenu)
gradbot
+2  A: 

You could also type

let contextMenu = new ContextMenuStrip() in mainForm.ContextMenuStrip <- contextMenu

This is OCaml syntax, IIRC.

Edit: to be more clear: this is also valid (#light) F# syntax, since F# is based on OCaml.

I also don't recommend doing this, even though I like short programs.

cfern