It’s pretty funny to me when you think that you know some programming language quite well and suddenly you find out some feature, you’ve never heard before. I mean at all. That’s exactly what happened to me yesterday. Let’s see what’s that.

Generics are very useful in programming since we can avoid writing similar code multiple times. But when we start to complicate them too much, it quickly reduces the legibility of the code. Of course, I don’t claim that when we see that kind of “monster” somewhere, we should blame its creator for writing bad code, because in some scenarios that’s just inevitable. Let’s see the example of the mentioned structure:

namespace Project { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); PrintUserItems(new Dictionary<User, IEnumerable<Item>>()); Console.ReadKey(); } static void PrintUserItems(IDictionary<User, IEnumerable<Item>> userItems) { } } class User { } class Item { } }

Well, the example isn’t complicated but imagine some scenarios when having multiple generics parameters in couple methods – that’s not the nicest code, you’d like to read or fix. That’s when the mentioned C# feature comes into play – aliased generics. By using it we can refactor the above code as follows:

using System; using System.Collections.Generic; using UserItems = System.Collections.Generic.IDictionary<Project.User, System.Collections.Generic.IEnumerable<Project.Item>>; namespace Project { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); PrintUserItems(new Dictionary<User, IEnumerable<Item>>()); Console.ReadKey(); } static void PrintUserItems(UserItems userItems) { } } class User { } class Item { } }

Of course, when you want to invoke the method, the proper type shows up:

The problem with the above construction is that we need to specify explicitly all the namespaces, so that sucks a little. But on the other hand, we can simplify the code in the entire class. Which one is better? I leave it up to you.