---
source_url: https://www.pubnub.com/docs/sdks/c-sharp
title: C# API & SDK Docs 8.2.0
updated_at: 2026-05-18T12:49:26.198Z
sdk_name: PubNub C# SDK
sdk_version: 8.2.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# C# API & SDK Docs 8.2.0

PubNub C# SDK, use the latest version: 8.2.0

Install:

```bash
dotnet add package PubNub@8.2.0
```

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide will help you get up and running with PubNub in your C# application, covering environments like .NET Framework, .NET Core, Xamarin, etc.

The core PubNub concepts and API usage are consistent across different C# platforms.

:::note SDK packages
PubNub provides different NuGet packages optimized for various .NET environments:
* `Pubnub`: For .NET Framework 4.6.1+
* `PubnubPCL`: For .NET Standard 2.0+ (includes .NET Core, Xamarin)
* `PubnubUWP`: For Universal Windows Platform Choose the package that best suits your target platform during installation.
:::

## Prerequisites

Before we dive in, make sure you have:

* A basic understanding of C#
* A C# development environment (Visual Studio, Visual Studio Code, Rider)
* .NET Framework 4.6.1+ or .NET Core 2.0+ installed
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create an app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

To integrate PubNub into your project using the [NuGet](https://www.nuget.org/) package manager, choose the command relevant to your project type:

#### .NET CLI

```bash
# For .NET Core / .NET Standard / Xamarin
dotnet add package PubnubPCL

# For .NET Framework 4.6.1+
dotnet add package Pubnub

# For Universal Windows Platform (UWP)
dotnet add package PubnubUWP
```

#### Package Manager console in Visual Studio

```bash
# For .NET Core / .NET Standard / Xamarin
Install-Package PubnubPCL

# For .NET Framework 4.6.1+
Install-Package Pubnub

# For Universal Windows Platform (UWP)
Install-Package PubnubUWP
```

#### Source code

Clone the [GitHub repository](https://github.com/pubnub/c-sharp):

```bash
git clone https://github.com/pubnub/c-sharp
```

## Steps

### Initialize PubNub

You'll need to initialize the PubNub client with your unique keys to establish a connection to the PubNub network. This is the minimum configuration required to send and receive messages with PubNub in your application.

In a standard C# application (like a console app or backend service), you typically initialize PubNub at the application's entry point or within a dedicated service class.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

```csharp
// Configure PubNub
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) 
{
    SubscribeKey = "demo", // Use your own keys in production
    PublishKey = "demo",   // Use your own keys in production
    Secure = true
};

// Initialize PubNub
pubnub = new Pubnub(pnConfiguration);

Console.WriteLine("PubNub Initialized!");
```

This code configures and initializes PubNub within the `Main` method of a console application.

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/configuration) section of the SDK documentation.

### Set up event listeners

Listeners help the application react to events and messages. You can implement custom logic to respond to each type of message or event.

Add the `SetupListeners` method to your `App` class. In a console or backend application, listeners might log messages or trigger other business logic.

```csharp
// Set up listeners for messages, presence, and status events
static void SetupListeners() 
{
    var listener = new SubscribeCallbackExt(
        // Handle Message Events
        (pn, messageEvent) =>
        {
            Console.WriteLine($"Message Received: Channel={messageEvent.Channel}, Message={messageEvent.Message}");

            var messageData = messageEvent.Message as Dictionary<string, object>;
            if (messageData != null && messageData.ContainsKey("text"))
            {
                Console.WriteLine($"Parsed Text: {messageData["text"]}");
            }
        },
        // Handle Presence Events (optional)
        (pn, presenceEvent) =>
        {
            Console.WriteLine($"Presence Event: Channel={presenceEvent.Channel}, Event={presenceEvent.Event}, UUID={presenceEvent.Uuid}");
        },
        // Handle Status Events
        (pn, statusEvent) =>
        {
            if (statusEvent.Category == PNStatusCategory.PNConnectedCategory)
            {
                Console.WriteLine($"Connected to PubNub on channel(s): {string.Join(",", statusEvent.AffectedChannels)}");
            }
            else if (statusEvent.Category == PNStatusCategory.PNSubscriptionChangedCategory)
            {
                Console.WriteLine($"Subscription changed,Now connected to PubNub on channel(s): {string.Join(",", statusEvent.AffectedChannels)}");
            }
            else if (statusEvent.Category == PNStatusCategory.PNDisconnectedCategory)
            {
                Console.WriteLine("Disconnected from PubNub.");
            }
            else if (statusEvent.Error)
            {
                Console.WriteLine($"PubNub Status Error: {statusEvent.ErrorData.Information}");
            }
        }
    );
    pubnub.AddListener(listener);
    Console.WriteLine("PubNub Listeners Set Up.");
}
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/configuration#event-listeners) section of the SDK documentation.

### Create a subscription

Subscribing tells PubNub that you want to receive messages published to specific channels.

Add the `SubscribeToChannel` method to your `App` class. We call this in `Main()` after setting up listeners.

```csharp
// Subscribe to a channel to receive messages
static void SubscribeToChannel(string channelName)
{
    pubnub.Subscribe<string>() // Use object if message type is unknown/mixed
        .Channels(new string[] { channelName })
        .WithPresence() // Enable presence events 
        .Execute();

    Console.WriteLine($"Subscribed to channel: {channelName}");
}
```

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

Publishing sends messages to a specific channel for all subscribed clients to receive.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

Add the `PublishMessageAsync` method to your `App` class. We call this from `Main()` in our example. Using `async/await` is common in C# for I/O operations.

```csharp
// Publish a message to a channel using async/await
static async Task PublishMessageAsync(string channelName, Dictionary<string, object> message)
{
    try
    {
        var result = await pubnub.Publish()
            .Channel(channelName)
            .Message(message)
            .ExecuteAsync();

        if (!result.Status.Error)
        {
            Console.WriteLine($"Message Published! Timetoken: {result.Result.Timetoken}");
        }
        else
        {
            Console.WriteLine($"Publish Error: {result.Status.ErrorData.Information}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception during publish: {ex.Message}");
    }
}
```

### Run the app

Now it's time to see your application in action!

1. Build your C# project (e.g., `dotnet build`).
2. Run the compiled application (e.g., `dotnet run` or execute the `.exe` file).
3. Observe the console output. You should see messages indicating initialization, connection, subscription, and the results of any publish operations.
4. If you publish a message, you should see the "Message Received" output shortly after in the same console (since it's subscribed to the channel it's publishing to).
5. Run a second instance of the application to see messages published by one instance appearing in the other.
6. Press any key in the console window to exit the application cleanly.

Here's the expected output in the console:

```text
PubNub Initialized!
PubNub Listeners Set Up.
Subscribed to channel: my_channel
Message Published! Timetoken: 16788864001234567 // Timetoken will vary
Connected to PubNub on channel(s): my_channel
Message Received: Channel=my_channel, Message={"text":"Hello from C# Console!"}
Parsed Text: Hello from C# Console!
Press any key to exit...
```

## Complete example

```csharp
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using PubnubApi;

namespace PubNubGetStarted
{
    public class Program
    {
        private static Pubnub pubnub;

        
        public static async Task Main(string[] args)
        {   
            
            // Configure PubNub
            PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId")) 
            {
                SubscribeKey = "demo", // Use your own keys in production
                PublishKey = "demo",   // Use your own keys in production
                Secure = true
            };

            // Initialize PubNub
            pubnub = new Pubnub(pnConfiguration);

            Console.WriteLine("PubNub Initialized!");

            

            // Add listeners
            SetupListeners();

            // Subscribe to channel
            SubscribeToChannel("my_channel");

            // Publish a test message
            var message = new Dictionary<string, object> { { "text", "Hello from C# Console!" } };
            await PublishMessageAsync("my_channel", message);

            // The application will continue to run and receive messages 
            // until the user presses a key to exit
            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();

            // Cleanup before exiting
            pubnub.UnsubscribeAll<string>();
            pubnub.Destroy();
            Console.WriteLine("PubNub Destroyed.");
        }

        
        // Set up listeners for messages, presence, and status events
        static void SetupListeners() 
        {
            var listener = new SubscribeCallbackExt(
                // Handle Message Events
                (pn, messageEvent) =>
                {
                    Console.WriteLine($"Message Received: Channel={messageEvent.Channel}, Message={messageEvent.Message}");

                    var messageData = messageEvent.Message as Dictionary<string, object>;
                    if (messageData != null && messageData.ContainsKey("text"))
                    {
                        Console.WriteLine($"Parsed Text: {messageData["text"]}");
                    }
                },
                // Handle Presence Events (optional)
                (pn, presenceEvent) =>
                {
                    Console.WriteLine($"Presence Event: Channel={presenceEvent.Channel}, Event={presenceEvent.Event}, UUID={presenceEvent.Uuid}");
                },
                // Handle Status Events
                (pn, statusEvent) =>
                {
                    if (statusEvent.Category == PNStatusCategory.PNConnectedCategory)
                    {
                        Console.WriteLine($"Connected to PubNub on channel(s): {string.Join(",", statusEvent.AffectedChannels)}");
                    }
                    else if (statusEvent.Category == PNStatusCategory.PNSubscriptionChangedCategory)
                    {
                        Console.WriteLine($"Subscription changed,Now connected to PubNub on channel(s): {string.Join(",", statusEvent.AffectedChannels)}");
                    }
                    else if (statusEvent.Category == PNStatusCategory.PNDisconnectedCategory)
                    {
                        Console.WriteLine("Disconnected from PubNub.");
                    }
                    else if (statusEvent.Error)
                    {
                        Console.WriteLine($"PubNub Status Error: {statusEvent.ErrorData.Information}");
                    }
                }
            );
            pubnub.AddListener(listener);
            Console.WriteLine("PubNub Listeners Set Up.");
        }
        

        
        // Subscribe to a channel to receive messages
        static void SubscribeToChannel(string channelName)
        {
            pubnub.Subscribe<string>() // Use object if message type is unknown/mixed
                .Channels(new string[] { channelName })
                .WithPresence() // Enable presence events 
                .Execute();

            Console.WriteLine($"Subscribed to channel: {channelName}");
        }
        

        
        // Publish a message to a channel using async/await
        static async Task PublishMessageAsync(string channelName, Dictionary<string, object> message)
        {
            try
            {
                var result = await pubnub.Publish()
                    .Channel(channelName)
                    .Message(message)
                    .ExecuteAsync();

                if (!result.Status.Error)
                {
                    Console.WriteLine($"Message Published! Timetoken: {result.Result.Timetoken}");
                }
                else
                {
                    Console.WriteLine($"Publish Error: {result.Status.ErrorData.Information}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception during publish: {ex.Message}");
            }
        }
        
    }

} 
```

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct (ensure they match the ones in your PubNub Admin Portal if not using "demo")., Check for firewall restrictions that might block outbound connections to PubNub servers. |
| Message not received | Double-check that both publisher and subscriber are using the exact same channel name., Verify the message was published successfully (check for publish error logs)., Ensure the listener callback logic correctly handles incoming messages and logs them., Confirm the Subscribe call was executed after listeners were added. |
| Build/Compile errors | Ensure you've installed the correct PubNub NuGet package., Check that all necessary using PubnubApi; statements are present., Verify you're targeting a compatible .NET Framework/Standard version. |

## Next steps

Great job! 🎉 You've successfully created your first PubNub C# application. Here are some exciting things you can explore next:

### Build chat

* Learn about the [Unity Chat SDK](https://www.pubnub.com/docs/chat/unity-chat-sdk) for ready-to-use chat features.
* Add typing indicators and read receipts.

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/presence) to track online/offline status in detail.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/storage-and-playback) to store and retrieve past messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/access-manager) to secure your channels and grant permissions.
* Explore [Functions](https://www.pubnub.com/docs/serverless/functions/overview) to run serverless logic on your messages in-flight.
* Send push notifications via [Mobile Push Notifications](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/mobile-push).

### Real examples

* Explore our [C# GitHub repository](https://github.com/pubnub/c-sharp/) for more code samples and the SDK source.

### More help

* Check out the [C# SDK reference documentation](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.