Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining type aliases

Tags:

c#

types

One feature of Pascal I found very useful was the ability to name a data type, eg

type  person: record              name: string;              age: int;          end;  var  me: person;  you: person;  etc 

Can you do something similar in C#? I want to be able to do something like

using complexList = List<Tuple<int,string,int>>;  complexList peopleList; anotherList otherList; 

So that if I have to change the definition of the datatype, I can do it in one place.

Does C# support a way to achieve this?

like image 232
haughtonomous Avatar asked Feb 13 '12 09:02

haughtonomous


People also ask

What is a type alias?

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.

What is a type alias in C++?

Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types.

What are type aliases in Javascript?

A type alias is basically a name for any type. Type aliases can be used to represent not only primitives but also object types, union types, tuples and intersections.

What is a type alias in TS?

In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name.


1 Answers

Yes, it's possible. You can write:

using System; using System.Collections.Generic;  namespace ConsoleApplication12 {     using MyAlias = List<Tuple<int, string, int>>; } 

or, if declared outside the namespace:

using System; using System.Collections.Generic;  using MyAlias = System.Collections.Generic.List<System.Tuple<int, string, int>>;  namespace ConsoleApplication12 { } 

then use it as a type:

MyAlias test = new MyAlias(); 
like image 99
ken2k Avatar answered Sep 18 '22 13:09

ken2k