CodeBlanks Logo Icon CodeBlanks

Syntax receiver

C# course · Expert · Lesson 40/47

Learn to scan the AST during compilation with SyntaxReceiver.

Syntax receiver

A syntax receiver is an object that scans the syntax tree during compilation and collects interesting nodes. The generator calls the receiver for each syntax tree; the receiver accumulates, for example, class declarations that carry a certain attribute.

This is like compile-time reflection: you inspect the structure of code without running it. The collected nodes are later used for code generation.

Collecting and counting

A receiver usually holds a List<string> and adds an item for each matching node. At the end of compilation this list is passed to the generator, which emits code for each item.

In this lesson we simulate the receiver with a ClassCollector class: the OnClass method adds a name, and the Count property gives the total.

Exercise Collect with ClassCollector

Define a ClassCollector class. Give it a public List<string> Classes { get; } = new(); property, a public void OnClass(string name) method (with Classes.Add(name);), and a public int Count => Classes.Count; property. In Main, add three class names and print Console.WriteLine(collector.Count).

Show example solution
class ClassCollector { public List<string> Classes { get; } = new(); public void OnClass(string name) { Classes.Add(name); } public int Count => Classes.Count; }. In Main: collector.OnClass three times, Console.WriteLine(collector.Count);
Example solution:
using System;
using System.Collections.Generic;

class ClassCollector
{
    public List<string> Classes { get; } = new();
    public void OnClass(string name) => Classes.Add(name);
    public int Count => Classes.Count;
}

class Program
{
    static void Main()
    {
        var collector = new ClassCollector();
        collector.OnClass("UserDto");
        collector.OnClass("OrderDto");
        collector.OnClass("AccountDto");
        Console.WriteLine(collector.Count);
    }
}

Test yourself

  1. Complete the OnClass call

    collector.____;
    Show answer
    collector.OnClass("UserDto");
  2. Match each syntax receiver concept

    Syntax tree
    Parsed code tree
    OnClass
    Class node event
    Classes list
    Collected class names
  3. What does a syntax receiver collect?

    • Runtime errors
    • User input
    • Syntax tree nodes
    • Network packets
    Show answer

    Syntax tree nodes — Correct. The receiver collects syntax tree nodes.

All lessons in Expert