2

I have to use new to create new instances of dynamically created, anonymous object types that are based on existing base types, or interfaces, using object expressions:

let a = { new System.Object() with member x.ToString() = "F#" }

But in other cases, for example computation expressions, I don't have to write new at all:

type MaybeBuilder() =
    member this.Bind(x, f) = match x with
                             | None -> None
                             | Some a -> f a
    member this.Return(x) = Some x

let maybe = new MaybeBuilder()
ley maybe2 = MaybeBuilder()

I'd like to ask, when is new not an optional to write?

MiP
  • 5,846
  • 3
  • 26
  • 41
  • 3
    Possible duplicate of [When does an F# type need to be initialised using new?](https://stackoverflow.com/questions/3398916/when-does-an-f-type-need-to-be-initialised-using-new) – FoggyFinder Dec 18 '17 at 07:55
  • 1
    This is not a duplicate because it involves object expressions - the other answer does not. – Tomas Petricek Dec 18 '17 at 12:08

1 Answers1

1

Your two examples are using completely different language features, even though they use the same new keyword.

You are never required to use new to call a constructor, as in your second example (in contrast to C# where you must use it).

But in F#, the new keyword is also used for the object expression feature, as in your first example. It is needed there because there are different uses for curly braces in F#. The compiler only knows that you are writing an object expression because it sees { new.

TheQuickBrownFox
  • 10,544
  • 1
  • 22
  • 35
  • except when calling a constructor of a class that implements `IDisposable`, in which case omitting `new` results in a warning (mentioned in the linked question). – scrwtp Dec 18 '17 at 18:03