There is a project from several files. In file A a type synonym is declared, for example:

 using MyMap = Dictionary<int, string>; 

There is also a function that uses this type as a parameter or / and return value. Suppose this:

 public MyMap foo(MyMap map) { ... } 

Because the function is declared as public it is accessible from the outside, i.e. including from another file. However, due to the fact that the synonym of the type ( using ) can be used only within one file, the following solutions are obtained:

  1. Use the original type in file B , i.e. Dictionary<int, string> ;
  2. Add similar using to file B ;
  3. To refuse using and to make a full-fledged class MyMap (ie a wrapper over the dictionary).

Each approach has its pros and cons. I would like to understand which is more appropriate and why.

Maybe the problem should be solved differently (your option)?

  • one
    The easiest way to remove the synonym. Here you have not a particularly difficult type to regret the loss of a synonym. - nzeemin 1:28 pm
  • A @nzeemin more saying name simplifies understanding. In the example, this is not very visible, but by 'MyMap' is meant something meaningful. Therefore, the name is important. - 伪位蔚蠂慰位蠀蟿
  • 2
    For my taste, if there is something meaningful, with its own name - then it should not be a Dictionary<int, string> , but aggregate it. That is, for my taste, a class with a (private) field of type Dictionary<int, string> . - VladD
  • 2
    @alexolut in this case, the name is needed for the variable, not for the type. It is better to create a class then, at a minimum, you will simplify your life when refactoring. For example, if you need to suddenly rename the type. - Alex Krass
  • Try to put using MyMap = Dictionary<int, string>; after namespace XXX - Terrible

1 answer 1

A type synonym is primarily needed to shorten the full name of a class, if you do not want to include the entire namespace and litter intellisense and to resolve name conflicts. Sometimes a synonym is used for the convenience of a programmer writing a particular class.

The less you use inheritance and composition, the clearer your code will be. Everything needs to be done in moderation. Since you pass a fairly simple Dictionary class as a parameter, it makes no sense to create a wrapper. Call this parameter myMap and others will understand what it is.

Inheritance, including composition, is applied only if the behavior of the original class changes. Create new types only if you are programming a new unique behavior. And to understand a meaningful enough parameter name.

Therefore, in file A, create your own synonym if you, as a programmer, are more comfortable and understandable and name this parameter with a meaningful name. And in file B, just transfer the Dictionary. But if you prefer, add the using declaration to file B.