Alexander Rautenberg
Alexander Rautenberg

Reputation: 2225

F# Shortcut Syntax for Properties?

For the normal property getter/setter syntax

let mutable myInternalValue

member this.MyProperty 
    with get() = myInternalValue
    and set(value) = myInternalValue <- value

is there a shortcut, similar to the following in C#?

someType MyProperty { get; set; }

If there is one, I seem to be unable to find it...

Upvotes: 32

Views: 11468

Answers (3)

Tomas Petricek
Tomas Petricek

Reputation: 243096

There is no shortcut for creating get/set property in F#, but if you want a property with just get you can use the following simple syntax:

type Test(n) =
  let myValue = n * 2
  member x.Property = 
    // Evaluated each time you access property value
    myValue + 5

Since F# is a functional language, F# types are very often immutable. This syntax makes it very easy to define immutable types, so it also encourages you to use a good functional programming style in F#.

However, I agree that a shortcut for get/set property would be very useful, especially when writing some code that needs to interoperate with C# / other .NET libraries.

EDIT (5 years later...): This has been added in F# 3.0, as the answer from Ben shows :-)

Upvotes: 13

bentayloruk
bentayloruk

Reputation: 4101

F# 3 has auto-implemented properties so you can declare properties without declaring the backing field.

Example taken from Properties(F#) on MSDN:

type MyClass() =
    member val MyProperty = "" with get, set

Upvotes: 61

Richard
Richard

Reputation: 109100

is there a shortcut, similar to the following in C#?

I don't think so (nothing shown in "Expert F#"'s syntax summary), and the F# syntax is already quite brief compared to the full syntax needed in C#.

Upvotes: 2

Related Questions