# CSharp Compiler API — Validate C# Code (Roslyn Diagnostics) (`ihndev/dotnet-check`) Actor

Compile-check CSharp code and get structured compiler errors and warnings as JSON. Semantic Roslyn analysis of .NET (dotnet) syntax and types — no build artifacts, no code execution. Built for AI agents verifying LLM-generated code.

- **URL**: https://apify.com/ihndev/dotnet-check.md
- **Developed by:** [IHNDEV](https://apify.com/ihndev) (community)
- **Categories:** AI, Agents, Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

from $0.005 / snippet check

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js/docs.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python/docs.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## C# Compiler API — Validate .NET Code & Get Roslyn Diagnostics

Check C# code and get every compiler error and warning back as **structured JSON** — exact codes, messages, and line/column positions. Full semantic Roslyn analysis, **no build artifact, no code execution**.

**Input:**

```json
{ "mode": "snippet", "code": "Consle.WriteLine(\"hi\");" }
````

**Output:**

```json
{
  "success": false,
  "errorCount": 1,
  "diagnostics": [
    {
      "id": "CS0103",
      "severity": "error",
      "message": "The name 'Consle' does not exist in the current context",
      "file": "snippet.cs",
      "line": 1,
      "column": 1
    }
  ],
  "checkTimeMs": 412
}
```

### Why AI agents need this

LLMs generate C# they cannot compile. One call answers *"does this build?"* with exact error locations — enabling the loop that makes generated code reliable: **generate → check → fix → check**. Diagnostic IDs are raw compiler codes (`CS0103`, `CS8602`…), so an agent can look them up, fix them, or suppress them deliberately.

### Quick start

**API:**

```bash
curl -X POST "https://api.apify.com/v2/acts/<USERNAME>~dotnet-check/run-sync-get-dataset-items?token=<TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{ "mode": "snippet", "code": "var x = 1 + \"two\";" }'
```

**MCP (agents):** add this actor at `mcp.apify.com?tools=<USERNAME>/dotnet-check`.

### Input reference

| Field | Type | Default | Notes |
|---|---|---|---|
| `mode` | `snippet` | `project` | `snippet` | Snippet = in-memory semantic check. Project = full `dotnet build` with NuGet support. |
| `code` | string | — | Source to check (snippet mode). Top-level statements, classes, or full files. |
| `files` | array | — | Project mode: `{ "path", "content" }` objects. A `.csproj` is generated if you don't include one. |
| `targetFramework` | string | `net8.0` | `net8.0`, `net9.0`, `net6.0`, `netstandard2.0` |
| `languageVersion` | string | `latest` | `8`–`13` or `latest` |
| `outputKind` | string | `console` | `console` allows top-level statements; `classlib` for libraries |
| `nullable` | bool | `true` | Nullable reference type analysis (CS86xx warnings) |
| `treatWarningsAsErrors` | bool | `false` | |
| `strict` | bool | `false` | Also runs the emit phase (in memory, discarded) for the rare emit-only diagnostics |
| `packages` | string\[] | — | Project mode: `Id@Version`, e.g. `Newtonsoft.Json@13.0.3` |

### Output reference

Each run pushes one dataset item: `success`, `errorCount`, `warningCount`, `checkTimeMs`, `toolVersion`, `chargedEvents` (billing transparency), and `diagnostics[]` — always present, errors first, each with `id`, `severity`, `message`, `file`, `line`, `column`, `endLine`, `endColumn`.

### Pricing

| Event | Price | When |
|---|---|---|
| Snippet check | $0.005 | Per snippet-mode run — **a typical validation costs half a cent** |
| Project check | $0.03 | Per project-mode build (includes NuGet restore) |
| Actor start | $0.001 | Per run |

### Security model

- **Your code is never executed.** The default path performs semantic analysis only — no assembly is ever produced. Strict mode emits to memory and immediately discards it.
- **No user-supplied analyzers or build tasks** are ever loaded — these would execute arbitrary code at compile time, so they are excluded by design.
- **Sources are discarded after the run.** Nothing is logged or persisted beyond your own dataset output.

### Limits & good to know

- Snippet source up to 1 MB; project mode up to 100 files / 5 MB / 25 packages.
- Common NuGet packages restore from a prewarmed offline cache; unusual ones fetch from nuget.org and take longer.
- Project mode has a 120 s build timeout.
- Policy limits exit gracefully with a `status` message — they are never disguised as system errors.

### Roadmap

`nuget-audit` (vulnerability scanning), `dotnet-format-check`, F#/VB.NET checkers. Found an issue or need a feature? Open an issue on this actor — response time is part of the deal.

# Actor input Schema

## `mode` (type: `string`):

snippet = fast in-memory semantic check of the code field. project = full dotnet build of the files array (supports NuGet packages).

## `code` (type: `string`):

Source code to check (snippet mode). Top-level statements, classes, or full files all accepted.

## `files` (type: `array`):

Project mode: array of { "path": "Program.cs", "content": "..." }. Include a .csproj or one is generated from the other inputs.

## `targetFramework` (type: `string`):

Framework whose reference assemblies the code is checked against.

## `languageVersion` (type: `string`):

C# language version used for parsing. 'latest' follows the newest supported by the bundled Roslyn.

## `outputKind` (type: `string`):

Console allows top-level statements; classlib checks the code as a library.

## `nullable` (type: `boolean`):

Enable nullable reference type analysis (CS86xx warnings).

## `treatWarningsAsErrors` (type: `boolean`):

Report all warnings as errors, failing the check on any warning.

## `strict` (type: `boolean`):

Snippet mode: also run the emit phase (to memory, discarded) to catch rare emit-only diagnostics. Default off — the semantic check covers ~99% of build errors.

## `packages` (type: `array`):

Project mode only. Format: Id@Version, e.g. Newtonsoft.Json@13.0.3. Restored from the local cache first.

## Actor input object example

```json
{
  "mode": "snippet",
  "code": "Console.WriteLine(\"Hello from dotnet-check\");",
  "targetFramework": "net8.0",
  "languageVersion": "latest",
  "outputKind": "console",
  "nullable": true,
  "treatWarningsAsErrors": false,
  "strict": false
}
```

# Actor output Schema

## `result` (type: `string`):

JSON check result: success flag, error/warning counts, and diagnostics with compiler codes and line/column positions.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "code": "Console.WriteLine(\"Hello from dotnet-check\");"
};

// Run the Actor and wait for it to finish
const run = await client.actor("ihndev/dotnet-check").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "code": "Console.WriteLine(\"Hello from dotnet-check\");" }

# Run the Actor and wait for it to finish
run = client.actor("ihndev/dotnet-check").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "code": "Console.WriteLine(\\"Hello from dotnet-check\\");"
}' |
apify call ihndev/dotnet-check --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=ihndev/dotnet-check",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "CSharp Compiler API — Validate C# Code (Roslyn Diagnostics)",
        "description": "Compile-check CSharp code and get structured compiler errors and warnings as JSON. Semantic Roslyn analysis of .NET (dotnet) syntax and types — no build artifacts, no code execution. Built for AI agents verifying LLM-generated code.",
        "version": "0.1",
        "x-build-id": "g0STxoVjrOe7nLtoS"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/ihndev~dotnet-check/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-ihndev-dotnet-check",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/ihndev~dotnet-check/runs": {
            "post": {
                "operationId": "runs-sync-ihndev-dotnet-check",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/ihndev~dotnet-check/run-sync": {
            "post": {
                "operationId": "run-sync-ihndev-dotnet-check",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "mode"
                ],
                "properties": {
                    "mode": {
                        "title": "Mode",
                        "enum": [
                            "snippet",
                            "project"
                        ],
                        "type": "string",
                        "description": "snippet = fast in-memory semantic check of the code field. project = full dotnet build of the files array (supports NuGet packages).",
                        "default": "snippet"
                    },
                    "code": {
                        "title": "C# code",
                        "type": "string",
                        "description": "Source code to check (snippet mode). Top-level statements, classes, or full files all accepted."
                    },
                    "files": {
                        "title": "Project files",
                        "type": "array",
                        "description": "Project mode: array of { \"path\": \"Program.cs\", \"content\": \"...\" }. Include a .csproj or one is generated from the other inputs.",
                        "items": {
                            "type": "object"
                        }
                    },
                    "targetFramework": {
                        "title": "Target framework",
                        "enum": [
                            "net8.0",
                            "net9.0",
                            "net6.0",
                            "netstandard2.0"
                        ],
                        "type": "string",
                        "description": "Framework whose reference assemblies the code is checked against.",
                        "default": "net8.0"
                    },
                    "languageVersion": {
                        "title": "C# language version",
                        "enum": [
                            "latest",
                            "13",
                            "12",
                            "11",
                            "10",
                            "9",
                            "8"
                        ],
                        "type": "string",
                        "description": "C# language version used for parsing. 'latest' follows the newest supported by the bundled Roslyn.",
                        "default": "latest"
                    },
                    "outputKind": {
                        "title": "Output kind",
                        "enum": [
                            "console",
                            "classlib"
                        ],
                        "type": "string",
                        "description": "Console allows top-level statements; classlib checks the code as a library.",
                        "default": "console"
                    },
                    "nullable": {
                        "title": "Nullable reference types",
                        "type": "boolean",
                        "description": "Enable nullable reference type analysis (CS86xx warnings).",
                        "default": true
                    },
                    "treatWarningsAsErrors": {
                        "title": "Treat warnings as errors",
                        "type": "boolean",
                        "description": "Report all warnings as errors, failing the check on any warning.",
                        "default": false
                    },
                    "strict": {
                        "title": "Strict (emit) mode",
                        "type": "boolean",
                        "description": "Snippet mode: also run the emit phase (to memory, discarded) to catch rare emit-only diagnostics. Default off — the semantic check covers ~99% of build errors.",
                        "default": false
                    },
                    "packages": {
                        "title": "NuGet packages",
                        "type": "array",
                        "description": "Project mode only. Format: Id@Version, e.g. Newtonsoft.Json@13.0.3. Restored from the local cache first.",
                        "items": {
                            "type": "string"
                        }
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
