C# - What is the C# equivalent of C++ typedef?

The C# equivalent is a using alias directive


  using StringList = System.Collections.Generic.List<string>;
  

A quick review of C++ typedef

The syntax for C++ is: typedef declaration synonym. E.g. typedef list<string> StringList;


Using the C++ Standard Library, we could use following to create a templated list of type string and iterate through it.


  list<string> items;
  for (list<string>::const_iterator it = items.begin(); it != items.end(); it++)
  {
      string str = *it;
  }
  

We can simplify the above by creating a type alias using typedef.


  typedef list<string> StringList;
  
  StringList items;
  for (StringList::const_iterator it = items.begin(); it != items.end(); it++)
  {
      string str = *it;
  }
  

As an alternative to typedef, we could create a new class dervied from the original type with public accessibility.


  class CStringList : public std::list<std::string>
  {
  }
  
  CStringList items;
  for (CStringList::const_iterator it = items.begin(); it != items.end(); it++)
  {
      string str = *it;
  }
  

Article continues below Ad.

Ads by Google

What about C#?

C# doesn't support the typedef keyword, but just like C++, we have options.


1. Create a type synonym with a using alias directive. This is similar to typedef.


  using StringList = System.Collections.Generic.List<string>;
  ...
  
  StringList items = new StringList();
  foreach (var item in items)
  {
      Console.WriteLine(item);
  }
  

2. Create a new class derived from the original type


  class CStringList : List<string>
  {
  }
  ...
  
  CStringList items = new CStringList();
  foreach (var item in items)
  {
      Console.WriteLine(item);
  }
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath