Skip to main content

Command Palette

Search for a command to run...

Flipping Qubits: C# in Quantum Computing

Q# Helped a Bit

Updated
9 min read
Flipping Qubits: C# in Quantum Computing
T
TJ Gokken is an AI Systems Architect with a passion for bridging the gap between technology and practical application. Specializing in .NET frameworks and machine learning, TJ helps software teams operationalize AI to drive innovation and efficiency. With over two decades of experience in programming and technology integration, he is a trusted advisor and thought leader in the AI community.

Just a few days ago, I wrote an introductory article about the significance of Microsoft’s new quantum chip. In that article, I talked about something called qubits, which is a quantum computing term, and unlike the traditional bits, which can hold a value of 1 or 0, how they can hold both of these values at the same time.

Quantum stuff fascinates me and I love learning about it. The article and what I read on the chip led me to think if it was possible to demonstrate the concept of qubits, in my favorite language: C#.

Turns out it is not. That’s it, end of the blog.


Just kidding :-)

While it is true that we cannot use C# to demonstrate this wild concept, it is possible to use a language called Q# using Microsoft Azure Quantum Development Kit - QDK in short.

We can write quantum operations using Q#, and since it plays very nicely with .NET ecosystem, then use a standard console app to run these operations. No quantum hardware needed - how cool is that?

💡
I am not going to go into it in this article but it is possible to use quantum hardware to run your Q# code. You will need an Azure account with a quantum workspace. You can then submit jobs to Azure Quantum. See https://learn.microsoft.com/en-us/azure/quantum/install-overview-qdk for more information.

Project Setup

Going to keep this demo super simple - like flipping a coin. In this journey, we are going to come across a bunch of new terminology and I’ll do my best to explain them all. This first version is going to be super simple, and we will introduce some advanced stuff in the second part.

Flipping a coin is pretty easy and the values are either 0 and 1 but that is boring. So, let’s use a qubit and something called Hadamart gate.

OK, what now? What does a gate have to do with anything? Well, take the blue pill and I’ll show it to you.


Hadamart Gate

I can easily give you the formula and tell you that this gate is one of the most useful gates in quantum computing as it places the qubit into an equal superposition of both |0> and |1> states. But I am not going to go into all that and try to explain with a simple analogy.

💡
Just in case, you did not know, the name gate comes from logic gates. A logic gate, is a device that performs a Boolean function - a logical operation performed on one or more binary inputs that produces a single binary output. Yup, that’s from Wikipedia. The seven basic logic gates are AND, OR, XOR, NOT, NAND, NOR and XNOR. That’s from me :-)
💡
You may wonder why the states in quantum computing is defined as |0> and |1>. This is pronounced “ket zero” or “ket one” and it comes from something called Dirac notation (or bra-ket notation) used in quantum mechanics. See the Appendix A for more information and some light night time reading.

Imagine a light switch. It is either up (0) or down (1). This is how classic computers function. Now, in the world of quantum computing, we have something called a qubit, which is in a weird state where it is 0 and 1 at the same time. This special state of being both states at once is called superposition.

This Hadamart gate that we are talking about, is like a magic trick for qubits. Going back to our analogy, if you have a light switch that is definitely either up (0) or down (1) and you use the Hadamart gate on it, the light switch suddenly starts floating between up and down. It is both and neither at the same time until it is measured. When you decide to check (or measure in quantum language) the light switch, it has to decide to be either up or down, in other words 0 or 1. From there on, it behaves like the normal bit operators but this hovering effect gives quantum computers their unique power that classical computers struggle with.

Why, you might ask, this is powerful? Well, it gives us true parallelism. True multi-tasking.

Just imagine search operations. Instead of classical search where we search in a linear way, you can search an unsorted database all at once from multiple entry points. There are other advantages that it helps with but I do not want to go into them as it will require much more explanation. However, if you are curious, you may want to look up Quantum Interference and Entanglement.


OK, back to our project.

As much as I love using Visual Studio, QDK is not available for it, so we need to use Visual Studio Code. You’ll need to install .NET SDK and the Microsoft Azure Quantum Development Kit.

Then, just switch to the directory where you want your whole solution to be at (I called mine QuantumDemo) and initialize a new solution and run the following commands:

# 1. create the solution
dotnet new sln -n quantumdemo

# 2. create the q# project (a console template)
dotnet new console -lang Q# -o QuantumQsharp

# 3. create the c# console project
dotnet new console -o QuantumCsharp

# 4. add both projects to the solution
dotnet sln quantumdemo.sln add .\QuantumQsharp\QuantumQsharp.csproj
dotnet sln quantumdemo.sln add .\QuantumCsharp\QuantumCsharp.csproj

# 5. optionally, have the c# project reference the q# project
cd QuantumCsharp
dotnet add reference ..\QuantumQsharp\QuantumQsharp.csproj
cd ..

You can open your folder in VSC and see both projects.

If you want to run either project, you can simply run the command:

dotnet run --project .\QuantumQsharp\QuantumQsharp.csproj
 or

dotnet run --project .\QuantumQsharp\QuantumCsharp.csproj

OK, now that we are all setup, let’s add some code.

Hello Quantum World

We need to add a new file to our QuantumQSharp project. Let’s call it QuantumCoinFlip.qs. Then add this code to it:

namespace QuantumQsharp {
    open Microsoft.Quantum.Canon;
    open Microsoft.Quantum.Intrinsic;

    operation FlipQubit() : Result {
        // Allocate one qubit
        use qubit = Qubit();

        // Apply the Hadamard gate
        H(qubit);

        // Measure the qubit
        let result = M(qubit);

        // Reset the qubit to |0>
        Reset(qubit);

        // Return the measured result
        return result;
    }
}

Let’s unpack what is going on here.

We import a couple of quantum libraries so we can run quantum operations. We define a qubit and then apply the Hadamart gate to it. We measure the gate which forces the qubit to become either 1 or 0 with some probability. We practically flipped a coin in a quantum way.

The result is stored into a variable and returned.

And that’s all there is to it: create a qubit, toss it into superposition, measure the outcome, and hand that back. It’s a short but sweet way to show quantum randomness in action!

Now, let’s add some code to our console app top see this in action - add this to our Program.cs in the console project:

using Microsoft.Quantum.Simulation.Simulators;
using QuantumQsharp; // <--- This should match the Q# namespace

namespace QuantumCsharp;
class Program
{
    static void Main(string[] args)
    {
        using var sim = new QuantumSimulator();
        var result = FlipQubit.Run(sim).Result;
        Console.WriteLine($"We got: {result}");
    }
}

Make sure your QSharp project is not an .exe as it needs to be a library. If you see that it is an .exe in your .csproj, then delete that line and also delete Program.qs if it exists and then clean and rebuild the QSharp project.

I cannot stress this enough. For this to work, your Q# project needs to be a library, so if you have this line in your Q# .csproj file, just delete it:

<OutputType>Exe</OutputType>

If you run the console app now, we see the result that the flip of the coin is either 1 or 0. However, we need to run it multiple times to see the randomness and running with the code from the terminal is not the most ideal way to do that.

So, let’s change the Program.cs:

using System;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
using QuantumQsharp; // Make sure this matches the Q# namespace

class Program
{
    static void Main(string[] args)
    {
        using var sim = new QuantumSimulator();

        // Run the quantum operation 10 times
        for (int i = 0; i < 10; i++)
        {
            var result = FlipQubit.Run(sim).Result;
            Console.WriteLine($"Run {i + 1}: We got {result}");
        }
    }
}

Now, let’s run it again:

That’s more like it.

Final Thoughts

Well, what we did was a tiny step for humankind but a big step for us as we veered into quantum computing using C#- OK, Q# helped a little bit.

We only flipped one qubit, but even that simple program showcases how quantum mechanics can give us probabilities from a superposition.

Of course, we are running this code on a classical simulator so it’s not “true” superposition. As I mentioned at the beginning of this article, you can submit this job to Azure Quantum to see it run on a real quantum computer. It may be a bit of an overkill to flip the coin on a quantum machine, but all is fair in love and learning.

You can find the source code for this project here: https://github.com/tjgokken/QuantumDemo

In a follow up to this article, we will go beyond flipping coins and explore stuff like entangled qubits, quantum interference, look at some other gates, and maybe a sneak peek at some algorithms.


Appendix A: Dirac Notation (aka Bra-Ket notation)

Quantum mechanics deals with states that can be superpositions (combinations) of 0 and 1 (and more, if you go beyond qubits - yeah, it’s a thing and it is called a qutrit - look it up!). Physicists (and now quantum programmers) needed a compact, consistent way to represent those states mathematically.

So, enter Drac Notation, aka Bra-Ket notation.

  • A “ket,” written as |ψ⟩, represents a column vector in a complex vector space (think of it like a vector pointing to a specific direction in space).

  • A "bra" (⟨ψ|) is just the row vector version (useful for math, less for coding). OK, we leave that bad boy alone.

Now we know where Bra-Ket comes from.

  • |0⟩ is written as (1,0)ᵀ, meaning the qubit is in state 0.

  • |1⟩ is (0,1)ᵀ, meaning the qubit is in state 1.

When in superposition , a qubit state is represented as;

|ψ⟩ = α|0⟩ + β|1⟩

Read that as

"ket psi equals alpha ket zero plus beta ket one".

Yeah I know, it sounds like an invitation to a fraternity/sorority mixer.

Joking aside, it is basically shorthand for quantum math, and quantum computing just inherited it.

For our purposes, that’s all there to know. However, if you want some more light reading check out Appendix B.


Appendix B: Further Reading

If you're curious to learn more about quantum computing, here are some great books to check out:

Beginner-FriendlyQuantum Computing for Everyone – Chris Bernhardt
Introduction to quantum computing without overwhelming math.

Hands-On Coding (Q# & Python)Learn Quantum Computing with Python and Q# – Sarah Kaiser & Chris Granade
For developers who want to write real quantum code using Microsoft’s Q#.

Deeper Dive (Math & Theory)Quantum Computation and Quantum Information – Michael Nielsen & Isaac Chuang
OK, this one’s heavy. But if you’re serious about quantum computing, this is THE book.

Want a free hands-on resources?