Click here to Skip to main content
15,113,295 members
Articles / Programming Languages / C#
Posted 31 Mar 2011


1 bookmarked

Code Coverage And Generics

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
2 Apr 2011CPOL
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.


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. :)


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


About the Author

Andrew Rissing
United States United States
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.

So..If you're not moving forward, you're moving backwards.

Comments and Discussions

QuestionThanks Pin
RobRimmer2k822-Oct-12 0:53
MemberRobRimmer2k822-Oct-12 0:53 
AnswerRe: Thanks Pin
Andrew Rissing22-Oct-12 5:08
MemberAndrew Rissing22-Oct-12 5:08 
GeneralWhat do you mean by coverage? Pin
jeramyRR5-Dec-11 22:55
MemberjeramyRR5-Dec-11 22:55 
GeneralRe: Code coverage. As in, the percentage of the code covered (o... Pin
Andrew Rissing6-Dec-11 4:55
MemberAndrew Rissing6-Dec-11 4:55 
GeneralReason for my vote of 5 Very valuable information. Thanks fo... Pin
Manfred Rudolf Bihy1-Apr-11 4:59
professionalManfred Rudolf Bihy1-Apr-11 4:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.