Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Directive to declare a pseudo-type in C#

I inherited some source code that I am just starting to dig though, and i found the previous owner has made some use of the using directive as an alias for a List<T>, but I've never seen this specific approach before.

namespace MyNamespace
{
    using pType1 = List<type1>;
    using pType2 = List<List<type1>>;

     // classes here
}

Both of these elements are used quite heavily within the code and are also return types from several of the key methods within the code. I get what he was trying to accomplish with using a simple name rather than repeating List<type1> and List<List<type1>> over and over again. I'm debating whether to create a real type to replace the using statements, but before i spend the time, I was wondering if there were any pros/cons to keeping the current implementation.

like image 410
psubsee2003 Avatar asked Oct 09 '22 06:10

psubsee2003


2 Answers

Generally, if a data structure represents some entity in your application's domain model it should get its own type; it makes the code much clearer and understandable. On the other hand, if you just need a List<List<string>> for intermediate data processing there's no real benefit in making a proper type for that.

In your case, since the original dev went to the trouble of making an alias for the type it's logical that it would be used a lot, which points to the "represents an entity" scenario. If so, definitely go ahead and create a new type for the structure (possibly something more appropriate than bare lists and usually something defined in terms of interfaces rather than concrete classes, but that depends on what you 're actually modelling there).

like image 122
Jon Avatar answered Oct 13 '22 11:10

Jon


If that construct is used as heavily as you say, I would definitely replace it with (the) real types (explicitly write out the List or create a new type). If someone happens to change one of the type declarations, like

using pType1 = List<type2WhichType1InheritsFrom>;

because (s)he thinks the base version does something better without looking at all places where it is used, there might be some unwanted side effects.

like image 28
Matten Avatar answered Oct 13 '22 11:10

Matten