📜  Q# hello world - C# (1)

📅  最后修改于: 2023-12-03 15:19:37.489000             🧑  作者: Mango

Q# Hello World Tutorial for C# Programmers

If you're a C# programmer looking to explore quantum computing with Q#, then you're in the right place. In this tutorial, we'll go through how to write a simple "Hello World" program in Q# and integrate it with C# code.

Prerequisites

To follow this tutorial, you'll need to have the Microsoft Quantum Development Kit installed and set up on your machine.

Creating a Q# project

The first step is to create a new Q# project in Visual Studio. You can follow the steps provided in the official documentation.

Writing a "Hello World" Q# program

The next step is to write a simple "Hello World" program in Q#. Here's the code:

namespace HelloWorld {

    open Microsoft.Quantum.Primitive;

    operation SayHello() : Unit {
        Message("Hello, World!");
    }
}

This program defines a new operation called SayHello that takes no input and has a return type of Unit. The only thing it does is print the message "Hello, World!" to the console.

Integrating the Q# program with C# code

Now that we have a working Q# program, the next step is to integrate it with C# code. Here's what our C# code will look like:

using System.CommandLine;
using Microsoft.Quantum.Simulation.Simulators;

namespace HelloWorld
{
    class Program
    {
        static int Main(string[] args)
        {
            var command = new RootCommand
            {
                new Command("hello", "Says hello from the quantum world.")
            };

            command.Handler = CommandHandler.Create<string>(RunCommand);

            return command.InvokeAsync(args).Result;

            static void RunCommand(string subcommand)
            {
                using var qsim = new QuantumSimulator();
                qsim.Run(SayHello.Run);
            }
        }
    }
}

Our C# application uses the Microsoft.Quantum.Simulation.Simulators namespace to create a new QuantumSimulator instance, which is used to run our Q# program. The Run method is called with the name of the Q# operation we want to run (SayHello), and that's it!

Running the program

To run the program, navigate to the directory containing our C# project and run the following command:

dotnet run hello

You should see the message "Hello, World!" printed to the console.

Conclusion

Congratulations! You've just written your first Q# program and integrated it with C# code. The possibilities of quantum computing are endless, and now you're ready to explore them with the help of Q# and the Quantum Development Kit.