Declaring a type synonym in C#

Viewed 16939

I hope I missed this in the docs. Is there a way to declare a type synonym in C#?

7 Answers

@CountOren was close

sealed public class Name
{
    private readonly string _value;
    private Name(string value) { _value = value; }
    public static implicit operator string(Name name) { return name._value; }
    public static implicit operator Name(string value) { return new Name(value); }
}

Usage

Name myName = "John";

Some types are better to go as struct in which case remove sealed and replace class with struct. It is up to you if you want to have sealed in case you want to go with class at all.

This is not the most straightforward way to solve this problem but when I need a type synonym I create a class with implicit conversions to and from the target type, for example:

Given Name needs to be synonym to string, Then you can do the following:

public class Name
{
    public string Value;
    public static implicit operator string(Name name) { return name.Value; }
    public static implicit operator Name(string name) { return new Name {Value = name}; }
}

Which will give you the ability to use Name type around your code and the compiler will let you assign values to it as well from a string.

If you have the following method signature:

public void SomeMethodThatNeedsName(Name name)

You could do this:

SomeMethodThatNeedsName("aNameThatComesFromString")

Global usings are now possible in C#10

global using MyInt = System.Int64;

Related