Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace C# class example with a record #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 5 additions & 25 deletions csharp2fsharp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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
Expand Down