According to the last sentence on this MSDN page use
is to be preferred over using
. I've heard it elsewhere (this answer, for example). Why is this? I realize use
was added later. But what's the difference? On the surface, using
seems more useful because you can control when Dispose()
is called, and you can explicitly ignore the bound value (e.g., (fun _ -> ...)
) if needed.
相关问题
- F#: Storing and mapping a list of functions
- Multiplying a list of tuples by a tuple in F#
- Multiplying a string in F#
- F# odd pattern matching issues
- Why doesn't bindingRedirect affect FSharp.Core
相关文章
- FSharp.Data.JsonProvider - Getting json from types
- Signing an F# Assembly (Strong name component)
- Disposing the members that implement IDisposable
- Learning F#: What books using other programming la
- fsc.exe is very slow because it tries to access cr
- Extension methods for specific generic types
- F# Object Initialization with a Constructor
- F# Lazy Evaluation vs Non-Lazy
An example against
use
is better thenusing
:using
is better thanuse
asusing
can be written in one line whileuse
cannot.Example,
xx
is a function returning a value by a function fct from a resource which is opened byyy
using given parameterp
.I think that the reason for preferring
use
is just that the syntax is simpler. Many other language constructs could be expressed as functions (e.g.try .. with
,for
,while
, ...). If the language designers added a simpler syntax, why not use it...As I wrote in the earlier answer you referenced, you can precisely control the scope even when using
use
. (And this way, you can use it even in constructors ofobject expressionsclass declarations.) But most of the time, the automatic behavior is just fine (which makes the construct simpler thanusing
in C#).Whether you'll use
use
orusing
in situations where you need to control the scope explicitly is a matter of personal taste. If you don't like the explicit scoping ofuse
(which looks a bit weird, I admit, but works fine for me), you can useusing
.EDIT: In a class declaration, you cannot for example write:
because the scope of
a
would be (possibly) the whole lifetime of the instance. (Although I think this could be useful and it could add automatic implementation ofIDisposable
to your type). If you useusing
, you don't get this sort of trouble.You can control when dispose is called with
use
as well, just by using usual scoping contructs (like parens orbegin
-end
), e.g.But I think this is rarely useful. I think it is also rare to not want to name/utilize the
IDisposable
object.use
is more syntactically convenient, and 95% of the time does what you need, so I think that's why it's preferred.Personally, I prefer
use
tousing
for the same reason that I preferto
With the binding form, you can typically avoid a set of parentheses, and the association between the identifier and the value that it's being bound to are closer in space and easier to see.