…

Main menu

Tag Archives: generic namespaces

So, it’s been awhile since I’ve published a post on this site. Today I found myself answering a stack overflow post with essentially what I had planned on covering for this part of my series on generics in .net. So I figured that I would post the same content here. As a result, this 5th part is being publish out of order and before parts 2-4. Hopefully, it won’t be another year before I get around to posting those parts. So with that said, here is the post. Note that some of the concepts employed in this post will be covered in parts 2-4.

For those who work with multiple generic classes that share the same generic type parameters, the ability to declare a generic namespace would be extremely useful. Unfortunately, .Net (or at least C#) does not support the idea of generic namespaces. So in order to accomplish the same goal, we can use generic classes to fulfill the same goal. Take the following example classes related to a logical entity:

Then, through the use of partial classes you can separate the classes into separate nested files. I recommend using a Visual Studio extension like NestIn to support nesting the partial class files. This allows the “namespace” class files to also be used to organize the nested class files in a folder like way.

The above is a simple example of using an outer class as a generic namespace. I’ve built “generic namespaces” containing 9 or more type parameters in the past. Having to keep those type parameters synchronized across the nine types that all needed to know the type parameters was tedious, especially when adding a new parameter. The use of generic namespaces makes that code far more manageable and readable.