C# to JavaScript compiler

# How It Works

h5 is a source-to-source compiler that translates C# code into JavaScript. It allows you to write your application logic using C# and .NET libraries, while running it in a browser environment.

# Compilation Process

When you build an h5 project, the compiler performs the following steps:

  1. Parsing: Reads your C# source code and parses it into an abstract syntax tree (AST).
  2. Analysis: Analyzes the code for types, members, and dependencies. It resolves references to .NET libraries and other h5 assemblies.
  3. Translation: Converts the C# AST into an equivalent JavaScript AST. This involves mapping C# constructs (classes, methods, properties) to JavaScript prototypes and functions.
  4. Emission: Generates the final JavaScript code.
  5. Output: Writes the JavaScript files to the configured output directory.

# Runtime Environment

To bridge the gap between .NET and JavaScript, h5 relies on a small runtime library (h5.js). This library provides:

  • Type System: Emulation of C# classes, interfaces, enums, and generics in JavaScript.
  • Base Class Library: Implementations of core .NET types like System.String, System.Int32, System.Console, System.Collections.Generic.List<T>, etc.
  • Reflection: Metadata support for runtime type inspection.

Your compiled code depends on this runtime library to function correctly. When you use h5.json to generate an HTML file, it automatically includes h5.js before your application scripts.

# C# Features Support

h5 supports most modern C# features, including:

  • Classes & Structs: Fully supported with inheritance and polymorphism.
  • Interfaces: Supported.
  • Generics: Fully supported, including constraints.
  • Lambdas & Delegates: Translated to JavaScript functions.
  • LINQ: Supported via h5.Core or System.Linq.
  • Async/Await: Implemented using JavaScript Promises.
  • Events: Supported using standard .NET event patterns.
  • Attributes: Supported and can be used to control compilation behavior.

# Differences from Standard .NET

While h5 aims for high compatibility, there are some key differences due to the nature of the JavaScript environment:

  • Garbage Collection: Relies on the browser's JavaScript garbage collector.
  • Threading: JavaScript is single-threaded. System.Threading.Thread is not supported in the same way as .NET, but Task and async/await work seamlessly using the event loop.
  • File System: Direct file system access (System.IO) is limited or behaves differently in the browser (e.g., using LocalStorage or IndexedDB).