From 52f8b94a4742acf2752e8db5db0b9410751a86bc Mon Sep 17 00:00:00 2001 From: Mohammad Azhdari Date: Sat, 23 Mar 2024 18:57:57 +0330 Subject: [PATCH] Replace C# class example with a record --- csharp2fsharp.md | 30 +++++------------------------- 1 file changed, 5 insertions(+), 25 deletions(-) diff --git a/csharp2fsharp.md b/csharp2fsharp.md index 0a034b3..e0f9896 100644 --- a/csharp2fsharp.md +++ b/csharp2fsharp.md @@ -225,40 +225,21 @@ In C# you write null checks everywhere (no safety at compile time). In F#, you d ### Example 6: Basic types -This immutable C# class below is much easier to write in F#: +This immutable C# record: ```csharp -public class Foo -{ - public Foo (int bar, string baz) - { - this.bar = bar; - this.baz = baz; - } - - readonly int bar; - public int Bar - { - get { return bar; } - } - - readonly string baz; - public string Baz - { - get { return baz; } - } -} +public record Foo(int Bar, string Baz); static class FooFactory { static internal Foo CreateFoo() { - return new Foo(42, "forty-two"); + return new (42, "forty-two"); } } ``` -because it's just one line: +becomes: ```fsharp type Foo = { Bar: int; Baz: string } @@ -269,9 +250,8 @@ module FooFactory = ``` So then: -* Classes without behaviour (like the above Foo) are called "Records", they seem similar to structs but they are still reference types and allocated on the heap. They are immutable (once you create them, you cannot change their values underneath). * Static classes are "modules", like the "FooFactory" type above. -* In F#, there's no need to use the keyword "new" when creating instances of new classes or structs, except if the class being created implements IDisposable. +* In F#, there's no need to use the keyword "new" when creating instances of new classes, records or structs, except if the class being created implements IDisposable. ### Example 7: Order is important, and circular dependencies are the root of all evil