24

I am trying to use System.Data.Sqlite with F#. In C#, I have code like

 using (DbTransaction dbTrans = con.BeginTransaction()) {
     using (SQLiteCommand cmd = con.CreateCommand()) {
         //blahblah
     }
     dbTrans.Commit();
 }

But in F#, when I use the similiar two using above I got error of the type bool is not compatible with the type IDisposable... EDIT I am really sorry for my question. use would work in F# case. I just dont know how to close/delete my quesetions.

knocte
  • 16,941
  • 11
  • 79
  • 125
user8321
  • 275
  • 2
  • 6
  • 6
    I don't know whether you really need to delete the question. It isn't a bad question: it got an upvote, and two decent answers. – Benjol Feb 14 '11 at 06:40

2 Answers2

25

To add some details - if you need to explicitly mark the scope where command is valid (to get exactly the same behavior as in your C# example, where cmd id disposed of before calling Commit) you can write:

use dbTrans = con.BeginTransaction()
( use cmd = con.CreateCommand()
  cmd.BlahBlahBlah() )
dbTrans.Commit()

The scope is just a part of expression where the symbol is defined, so you can make it explicit using parentheses.

using is just an F# function that you could use before special syntax using use was added. Just FYI, the syntax looks like this:

using (con.BeginTransaction()) (fun dbTrans ->
  using (con.CreateCommand()) (fun cmd ->
    cmd.BlahBlahBlah() )
dbTrans.Commit() )

Writing the code using use is definitely a better idea (but you can define your functions like using to encapsulate more interesting behavior - e.g. transaction).

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
15

in f# it's

use dbTrans = new con.BeginTransaction ()

and

use cmd = con.CreateCommand()

these will dispose when your function ends

Alex
  • 2,342
  • 1
  • 18
  • 30