1

Assume the following code:

let fn () =
  use a = new System.IO.StreamWriter ("d:\\test.txt")
  a

let b = fn ()
b.Write "t"

It gives following error:

ObjectDisposedException: Cannot write to a closed TextWriter.

Why is that?

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
Oldrich Svec
  • 4,191
  • 2
  • 28
  • 54

3 Answers3

8

use is scoped to the function fn so when a is returned it also disposed.

The easiest way to cure this is:

let fn () =
  let a = new System.IO.StreamWriter ("d:\\test.txt")
  a

let main() = 
  use b = fn ()
  b.Write "t"
main()
Robert
  • 6,407
  • 2
  • 34
  • 41
5

To add a bit more to Robert's (correct) answer: you can achieve even finer control over the scope of use with scoping constructs (parentheses or begin/end). See Brian's answer to a related question.

Community
  • 1
  • 1
Daniel
  • 47,404
  • 11
  • 101
  • 179
2

The resource will be disposed as soon as the variable (in your case a) goes out of scope.

This means that after the call to fn the StreamWriter will already be disposed.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614