In C#, is there a way to define a type synonym?

407 Views Asked by At

In my C# project, I have a need for a long union type of the form:

System.Tuple<..., ..., ...>

where the ...'s are components with names long enough that the whole tuple type declaration stretches for an entire line's width.

Does C# support a way to shorthand this?

I'm imagining something like Haskell's type synonyms, where I can declare a short type name to use in place of the long one as easily as I can declare a new variable.

I tried using var, but since I need to to declare the type of a parameter to delegate, I get an error reading "the contextual keyword 'var' may only appear within a local variable declaration or in script mode"; it appears that simply using var will not work for my case.

2

There are 2 best solutions below

0
kkica On BEST ANSWER

There is:

using MyAlias = MyLongType

It is called using alias directive. It also works for Namespaces. More information here.

However this works only inside only 1 file. You either need to write it in every file you will use it, or use the workaround:

Inherit from the class with the long type, and don't add anything to the functionality.

Example:

class  MyAlias: MyLongType{}
2
TheGeneral On

Straight from the documentation

using directive (C# Reference)

To create an alias for a namespace or a type. This is called a using alias directive.

using Project = PC.MyCompany.Project;

Eg

using ShortTypeName = My.Very.Silly.Long.TypeName.That.is.VerySuspiciousAndProbablyShouldBeRefactoredAnyway;`
using ShortOtherTypeName = My.Very.Silly.Long.TypeName.That.is.VeryOtherSuspiciousAndProbablyShouldBeRefactoredAnyway;`

internal class Program
{
    private (ShortTypeName , ShortOtherTypeName ) _myLovelyTuple;