Alias any type in C# 12

C# 12 has numerous amazing features. One of the interesting features is Primary Constructors and another interesting feature is the use of aliases of any type and not just named types. What it does mean? It means that now we can create aliases for tuple types, array types, and pointer types.

So, in this article, we are going to learn the Alias Any Type.

What is Alias any type?

Alias any type is a feature introduced in C# version 12. This feature allows us to use aliases of any type.

So, the code snippet below was not valid before C# 12.

using AddParam = (int a, int b);

But, the above code snippet is valid in C# 12 onwards.

How to implement Alias of any type?

So far, we have a basic concept of the feature, now it’s time to understand the approach with the help of a code snippet.

Let’s demonstrate this by using a Add() method to sum 2 values.

public int AddValue(int a, int b)
{
    return a + b;
}

In the above code snippet, we are just creating a method which accepts 2 integer values and give results by adding them.

Next, create the object of the class and access the method by passing parameters of the same data type.

Calculator calculator = new Calculator();
int result  = calculator.AddValue(10, 20);
Console.WriteLine(result);

Here, we are using the traditional ways of passing parameters to a method and then executing them.

Now, let’s rewrite the same code snippet using the C# 12 feature i.e. alias any type.

First, add this code in the namespace area:

using AddParam = (int a, int b);

Now, create a class Calculator which contains a method AddValue():

public class Calculator
{
    public int AddValue(AddParam param)
    {
        return param.a + param.b;
    }
}

Here, we are using AddParam as a parameter to the method AddValue(). And, this is to note that AddParam is declared as an alias type.

Finally, add the code snippet below to execute and print the result:

Calculator calculator = new Calculator();
AddParam param = (50, 120);
int result = calculator.AddValue(param);
Console.Write(result);

In this code snippet, we are creating the object of the class Calculator. Then we use the AddParam alias and assign 2 integer values. To call the AddValue() method we pass the parameter which is an AddParam alias.

Here is the complete code snippet to demonstrate an alias of any type in C# 12.

using AddParam = (int a, int b);

Calculator calculator = new Calculator();
AddParam param = (50, 120);
int result = calculator.AddValue(param);
Console.Write(result);

public class Calculator
{
    public int AddValue(AddParam param)
    {
        return param.a + param.b;
    }
}

Hope, this article is helpful to you.

Leave a Comment

RSS
YouTube
YouTube
Instagram