Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Shortcut Syntax for Properties?

Tags:

f#

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...

like image 598
Alexander Rautenberg Avatar asked Oct 12 '10 10:10

Alexander Rautenberg


3 Answers

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
like image 144
bentayloruk Avatar answered Nov 04 '22 07:11

bentayloruk


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 :-)

like image 32
Tomas Petricek Avatar answered Nov 04 '22 06:11

Tomas Petricek


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#.

like image 1
Richard Avatar answered Nov 04 '22 06:11

Richard