Blazor  

Azure Digital Twins: Simulating Real-World Environments using C# Examples

Introduction

In today’s hyper-connected world, organizations are increasingly looking to create digital replicas of real-world systems to gain deeper insights, optimize operations, and predict outcomes. This concept, known as the Digital Twin, enables industries to model physical environments, assets, and processes in a virtual setting.

Azure Digital Twins, a managed service from Microsoft, brings this concept to the cloud. It allows you to model entire environments, factories, buildings, energy grids, supply chains, or even cities using digital models and relationships. With integration into IoT, AI, and analytics services, it enables a new level of simulation and decision-making.

In this article, we’ll explore the core concepts of Azure Digital Twins, its architecture, and walk through C# examples for building and interacting with twin models.

Why Azure Digital Twins?

Azure Digital Twins offers.

1. Real-time simulation: Mirror real-world data and processes digitally

Azure Digital Twins allows organizations to create live, digital replicas of their physical environments. Any changes in the real world, like temperature adjustments, machine status updates, or room occupancy, are immediately reflected in the twin. This enables continuous monitoring and provides a powerful foundation for running simulations that guide better decision-making.

2. IoT integration: Connect IoT devices for live telemetry

With built-in integration to Azure IoT Hub, devices and sensors can send telemetry data directly into Digital Twins. This ensures that the digital models always reflect the current state of assets, machines, or spaces. For example, temperature sensors in a factory can update the twin in real time, allowing managers to quickly respond to anomalies.

3. Spatial intelligence: Model complex relationships between entities

Unlike traditional IoT systems that focus on individual devices, Azure Digital Twins emphasizes relationships and dependencies. Assets, rooms, equipment, and people can all be modeled in a graph structure, showing how they interact. For example, a room can belong to a floor, which belongs to a building, giving organizations deeper insights into how changes in one part affect the whole environment.

4. Predictive analytics: Simulate “what-if” scenarios

Beyond real-time monitoring, Azure Digital Twins enables businesses to run predictive simulations. This allows users to test different scenarios, like forecasting energy usage if occupancy doubles, or predicting machine failures based on usage patterns. Such insights help organizations move from reactive responses to proactive and preventive strategies.

5. Integration with Azure ecosystem: Works seamlessly with IoT Hub, Azure Functions, Event Grid, Synapse Analytics, and Power BI

Azure Digital Twins doesn’t work in isolation; it integrates seamlessly with the broader Azure ecosystem. Data can flow from IoT Hub into Digital Twins, trigger automation with Azure Functions, stream through Event Grid, be analyzed in Synapse Analytics, and visualized in Power BI dashboards. This end-to-end integration provides a complete solution for monitoring, simulating, and optimizing operations.

This makes it ideal for industries such as manufacturing, smart buildings, energy, supply chain, and healthcare.

Core Concepts

  • Digital Twin Definition Language (DTDL): A JSON-like language to define digital twins, their properties, telemetry, and relationships.

  • Graph-based modeling: Twins are represented as nodes, and relationships as edges, forming a knowledge graph.

  • Data Ingress/Egress: Ingest data from IoT devices, business apps, or services, and push results into analytics tools.

  • APIs and SDKs: Developers can use REST APIs, SDKs (such as .NET, Java, and Python), and Azure CLI for interaction.

Azure Digital Twins Architecture

A typical architecture looks like this.

  • IoT Devices send telemetry to the IoT Hub.

  • Azure Digital Twins consumes the data and updates the twin states.

  • Azure Functions / Stream Analytics perform transformations or trigger actions.

  • Data is visualized in Power BI or processed in Azure Synapse for analytics.

This creates a live, digital replica of physical systems.

Step 1. Define a Twin Model

A DTDL model for a smart room could look like this.

  
    {
  "@id": "dtmi:example:Room;1",
  "@type": "Interface",
  "displayName": "Room",
  "contents": [
    {
      "@type": "Property",
      "name": "Temperature",
      "schema": "double"
    },
    {
      "@type": "Property",
      "name": "Humidity",
      "schema": "double"
    },
    {
      "@type": "Telemetry",
      "name": "MotionDetected",
      "schema": "boolean"
    }
  ]
}
  

This defines a Room twin with properties (temperature, humidity) and telemetry (motion detection).

Step 2. Connecting with C#

To interact with Azure Digital Twins, install the Azure Digital Twins client.DigitalTwins.Core package.

  
    dotnet add package Azure.DigitalTwins.Core
dotnet add package Azure.Identity
  

Step 3. Authenticate and Create a Client

  
    using Azure.DigitalTwins.Core;
using Azure.Identity;
using System;

class Program
{
    static void Main()
    {
        string adtInstanceUrl = "https://<your-digital-twins-instance>.api.<region>.digitaltwins.azure.net";

        var credential = new DefaultAzureCredential();
        var client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);

        Console.WriteLine("Connected to Azure Digital Twins!");
    }
}
  

Here, we authenticate using Azure AD via DefaultAzureCredential .

Step 4. Upload the Model

  
    using System.Collections.Generic;
using System.IO;

class ModelsExample
{
    public static void UploadModel(DigitalTwinsClient client)
    {
        string modelPath = "RoomModel.json";
        string modelContent = File.ReadAllText(modelPath);

        var models = new List<string> { modelContent };
        client.CreateModels(models);

        Console.WriteLine("Model uploaded successfully!");
    }
}
  

Step 5. Create a Digital Twin Instance

  
    using Azure.DigitalTwins.Core;
class TwinExample
{
    public static void CreateTwin(DigitalTwinsClient client)
    {
        string twinId = "Room1";

        var twinData = new BasicDigitalTwin
        {
            Id = twinId,
            Metadata = { ModelId = "dtmi:example:Room;1" },
            Contents =
            {
                { "Temperature", 22.5 },
                { "Humidity", 45.0 }
            }
        };

        client.CreateOrReplaceDigitalTwin(twinId, twinData);
        Console.WriteLine($"Digital twin '{twinId}' created.");
    }
}
  

This creates a twin instance named Room1 with temperature and humidity values.

Step 6. Update a Twin

  
    using Azure.DigitalTwins.Core;
using Azure.JsonPatch;

class UpdateExample
{
    public static void UpdateTwin(DigitalTwinsClient client)
    {
        string twinId = "Room1";
        var update = new JsonPatchDocument();
        update.AppendReplace("/Temperature", 24.0);
        update.AppendReplace("/Humidity", 50.0);

        client.UpdateDigitalTwin(twinId, update);
        Console.WriteLine($"Digital twin '{twinId}' updated.");
    }
}
  

Step 7. Query Digital Twins

  
    class QueryExample
{
    public static void QueryTwins(DigitalTwinsClient client)
    {
        string query = "SELECT * FROM digitaltwins WHERE Temperature > 23";

        var queryResult = client.Query<BasicDigitalTwin>(query);

        foreach (var twin in queryResult)
        {
            Console.WriteLine($"Twin ID: {twin.Id}, Temperature: {twin.Contents["Temperature"]}");
        }
    }
}
  

This retrieves all rooms where the temperature exceeds 23°C.

Step 8. Establish Relationships

Digital Twins support relationships (e.g., a Room belongs to a Building).

  
    class RelationshipExample
{
    public static void CreateRelationship(DigitalTwinsClient client)
    {
        string relationshipId = "Room1-Building1";
        var relationship = new BasicRelationship
        {
            Id = relationshipId,
            SourceId = "Room1",
            TargetId = "Building1",
            Name = "contains"
        };

        client.CreateOrReplaceRelationship("Room1", relationshipId, relationship);
        Console.WriteLine("Relationship created between Room1 and Building1.");
    }
}
  

Real-World Use Cases

  • Smart Buildings: Azure Digital Twins allows facility managers to create virtual models of entire buildings, including rooms, HVAC systems, lighting, and occupancy sensors. By analyzing live data, they can optimize energy usage, improve comfort, and detect anomalies such as equipment malfunctions. For example, if a room is unoccupied, the system can automatically adjust heating and lighting to reduce costs.

  • Manufacturing: Factories can build digital replicas of machines, production lines, and workflows to monitor performance and predict failures. By integrating IoT data into Digital Twins, manufacturers can simulate “what-if” scenarios, identify bottlenecks, and improve throughput. Predictive maintenance becomes possible, reducing downtime and extending the lifespan of expensive equipment.

  • Healthcare: Hospitals and clinics can model patient rooms, wards, and medical devices to ensure efficient operations. For example, real-time occupancy data can help optimize patient flow, while equipment telemetry can alert staff about the need for preventive maintenance. Digital Twins can even simulate emergency scenarios to improve response times.

  • Energy and Utilities: Energy providers can model grids, power plants, and renewable sources to monitor demand and distribution. By simulating load patterns, utilities can forecast demand spikes, prevent outages, and balance renewable energy inputs like solar or wind. This leads to more reliable service and better resource management.

  • Supply Chain and Logistics: Digital Twins can represent warehouses, fleets, and distribution networks to provide end-to-end visibility. Businesses can simulate disruptions, such as delays or shortages, and identify alternative routes or suppliers. This proactive approach helps reduce risks, control costs, and ensure the timely delivery of goods.

Conclusion

Azure Digital Twins enables organizations to go beyond simple IoT monitoring by creating real-time digital replicas of physical assets and environments. This graph-based modeling approach helps businesses understand not only device data but also the relationships and dependencies between systems, making simulations and predictive analytics possible.

With the C# SDK, developers can easily define models, create and update twins, and query data while integrating with services like IoT Hub, Functions, and Power BI. This combination allows enterprises to achieve greater efficiency, resilience, and innovation.

In essence, Azure Digital Twins bridges the gap between the physical and digital worlds, empowering industries to optimize operations today and prepare for the smart, data-driven systems of the future.