Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Code Coverage And Generics

5.00/5 (7 votes)
2 Apr 2011CPOL 16.9K  
How to get that last little nagging line to be covered...
I was recently trying to achieve a perfect 100% code coverage (don't ask) for a particular class I was working on, when I ran across an annoying problem.

A generic constructor...

The following code would only give me partial coverage when executed:

public class GenericMethod<T> where T : new()
{
  ...
  T item = new T();
  ...
}


In and of itself, not a very daunting looking line. But alas, it was a worthy foe. For without proper documentation and explanation, Visual Studio indicated that I was only partially covering this simple line.

After much Googling, I still didn't come up with any answers. So, after some head scratching, I finally tried a struct, because up until then, all of my unit tests were using classes.

VoilĂ !

Visual Studio complained no more and neither did I.

So, if you're ever in dire need of 100% code coverage and run across a partially covered line in a generic method, try using both classes and structs.

Granted, I could have restricted the type more, but I needed to support both. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)