Skip to main content

C# Inference API

The ONNX Runtime C# API provides .NET integration for running ONNX models in Windows, Linux, and cross-platform applications. This guide covers the complete C# API with real examples.

Installation

NuGet Package

Package Manager Console

Quick Start

Here’s a minimal C# example:

InferenceSession Class

Creating a Session

From file path:
From byte array:
With pre-packed weights container:

Session Properties

Running Inference

Basic inference:
Specify output names:
With RunOptions:

Model Metadata

SessionOptions

Configure session behavior:

RunOptions

Configure individual inference runs:

Working with Tensors

DenseTensor

NamedOnnxValue

Execution Providers

Adding Execution Providers

CUDA:
CUDA with options:
TensorRT:
DirectML (Windows):
CoreML (macOS):
Check available providers:

OrtValue API

Lower-level tensor API for advanced scenarios:

Complete Example: Image Classification

IOBinding for Advanced Scenarios

Use IOBinding for zero-copy inference with GPU memory:

Multi-Threading

InferenceSession is thread-safe for inference:

Error Handling

Supported Data Types

Best Practices

Always dispose InferenceSession and inference results using using statements to prevent memory leaks.
Creating a session is expensive. Create once and reuse for multiple inferences.
Choose the right execution provider for your hardware (CUDA for NVIDIA GPUs, DirectML for Windows, etc.).
Set GraphOptimizationLevel to ORT_ENABLE_ALL for best performance.
InferenceSession.Run() is thread-safe, so you can safely call it from multiple threads.

Next Steps

Model Optimization

Learn how to optimize models for production

Execution Providers

Configure hardware acceleration