Skip to content

C#: a local with no initialiser and no declared type (or with "Inferred" ticked) is generated as var x;, which fails with CS0818 #355

Closed

Description

@matt-edmondson

What's wrong

CSharpGenerator.GenerateVariableDeclaration uses var whenever IsTypeInferred is true or Type is null, and it does so even when there is no initial value:

// Use type or var for type inference
string type = varDecl.IsTypeInferred || varDecl.Type is null
? "var"
: MapToCSType(varDecl.Type);

C# can only infer a var type from an initialiser. Without one, var x; is error CS0818 ("Implicitly-typed variables must be initialized").

The generator already handles this for a held (file- or namespace-scope) variable. At lines 1825-1838 it replaces var with the initialiser's type, or with object plus a note. A local never reaches that fallback, so line 1861 writes var x exactly as computed.

The other typed targets fall back on the same input:

  • C++ writes std::any x (CppGenerator.cs, "auto needs an initializer to deduce from")
  • Rust writes an explicit unknown-type annotation
  • Go writes var x <type>
  • Python writes x = None

C# is the only target whose output does not compile.

Failure scenarios

  1. A function body containing new VariableDeclaration("x"). Type and InitialValue are both null, the generated C# is var x;, and compilation fails with CS0818.
  2. In the editor:
    • Add the catalog's "Variable" node, new VariableDeclaration("value", "int") (Coder.Graph/AstNodeCatalog.cs:63).
    • Tick its "Inferred" flag (Coder.Graph/AstFields.cs).
    • The C# preview changes from int value; to var value;, which does not compile, even though the declaration still says int.
    • Clearing the Type field instead gives the same result.

Suggested fix

Emit var only when InitialValue is not null. Otherwise:

  • use the declared type when there is one, even if IsTypeInferred is set
  • fall back to UnknownTypeName (object) with an inexpressible note when there is none

This matches the existing fallback for held variables and what C++, Rust and Go do.

Acceptance criteria

  • new VariableDeclaration("x") in a method body generates object x;, with a note.
  • new VariableDeclaration("x", "int") { IsTypeInferred = true } with no initialiser generates int x;.
  • var is still emitted when an initialiser is present.
  • These cases are added to Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs, so they are compiled and not only compared as text.

Activity

  1. added
    bug
    on Oct 30, 2026
  2. matt-edmondson commented on Oct 30, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions