Generics helps in the following ways to write code.
- Code reuse, performance and type safety
- Creation of custom generic classes, methods, interfaces and delegates
- Creation of Generic Collection classes
- Retrieving information of the types used in generic data type at run-time
- Better performance
The code below shows a generic method with different type parameters such as int, char and double typed parameters.
Code Snippet : FunctionTemplates Example
public class FunctionTemplates
{
public void Show<TypeOfValue>(string message, TypeOfValue value)
{
Console.WriteLine("{0}:{1}", message, value);
}
}
Code Snippet : FunctionTemplates Driver Example
using System;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Hello
{
class Driver
{
static void Main(string[] args)
{
FunctionTemplates p = new FunctionTemplates();
p.Show<int>("Integer", 10);
p.Show<char>("Character", 'E');
p.Show<double>("Decimal", 231.78);
}
}
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:
