C# for a TypeScript developerMethods, properties, and the class body
No narration yet
Module 1 · Lesson 213 min

Methods, properties, and the class body

A class body holds members: fields, properties, and methods. Coming from TS, methods are familiar and properties have a twist worth learning early, because Fusion code is full of them.

A method is a function that lives on a type. The signature reads left to right: access modifier, optional async, return type, name, parameters. void is the return type for "returns nothing" (like a TS : void). The single biggest reading skill is parsing that signature fluently.

Method signatures, annotated
public int Add(int a, int b) => a + b;          // expression-bodied, returns int
public void Log(string message) { /* ... */ }   // returns nothing (void)
public async Task<int> CountAsync() { /* ... */ }// async, returns a Task<int>
private string Format(decimal cost) { /* ... */ }// private helper

Note => on the first line. An expression-bodied member is C#'s arrow shorthand for a method whose whole body is one expression: public int Add(int a, int b) => a + b; is the same as { return a + b; }. You'll see it constantly on small methods and property getters, and it reads just like a TS arrow function.

Now the twist. TS has one concept, the class field. C# splits it into two.

Field vs property
public class Example
{
    private readonly IRepo _repo;              // FIELD: a raw slot, usually private

    public string Name { get; init; } = "";    // PROPERTY: get/init accessors, public
    public int Count { get; private set; }      // PROPERTY: public read, private write
    public bool IsEmpty => Count == 0;          // computed PROPERTY, no backing storage
}

A field is a plain variable slot. Fusion uses fields for private, injected dependencies, by convention prefixed with an underscore (_repo, _utcNow). A property looks like a field to callers (example.Name) but is really a pair of accessors, get and set, that let the type control reads and writes. { get; init; } means "readable always, settable only during construction," which is how the domain gets immutability. { get; private set; } means "the outside can read it, only this class can change it." And a getter with => and no set is a computed value, like a TS getter.

Practice

Try it yourself

Recall

Property versus field

Two words that look the same to a TS eye but aren't.

In C#, what's the difference between a field and a property, and which one does Fusion code expose publicly?

Quiz

Reading a signature

You see public async Task<Result<FlightNumberVo>> Create(string? value). Reading left to right, what does each part tell you?