Q# – Parameterized Type

Parameterized types are specified in generic classes. Generics in C# is powerful feature which defines the type-safe data structures. They are similar to templates in C++. The parameters can be typed by using generics in methods and classes. The framing of data type is deferred till the class or the method is declared and instantiated &  executed by client code.  They reduce the overhead of  following operations :

  • Boxing
  • UnBoxing
  • Type Casting of Variables and objects.

The code snippet below shows ParameterizedTypes Class which takes a generic type parameter ’T’. 

    public class ParameterizedTypes<T>
    {

        private T data;

        public T value
        {

            get
            {
                return this.data;
            }
            set
            {
                this.data = value;
            }
        }
    }

The Driver class has Main method, in which ParameterizedTypes Class is instantiated as string and float. The constructor accepts the required type for ParameterizedTypes class. 

using System;

using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;

namespace Hello
{
    class Driver
    {
        static void Main(string[] args)
        {

            ParameterizedTypes<string> name = new ParameterizedTypes<string>();
            name.value = "Parameterized Types";

            ParameterizedTypes<float> version = new ParameterizedTypes<float>();
            version.value = 7.0F;

            Console.WriteLine(name.value);

            Console.WriteLine(version.value);
        }
    }
}

Run the following commands  to execute the project in Visual Studio Code:

^F5 

In the terminal, you can execute the build by running the command below.

dotnet run

The screenshot of the output is attached below:

Leave a comment