Click here to Skip to main content
Click here to Skip to main content

Simple Source Line Counter in C# for C#

By , 24 Jan 2005
 

A Simple C# Line Counter

What is it?

A stand-alone utility that counts the lines of code in C# source files.

My searches on CP for source code line counters yielded some nice alternatives. However, I wanted something that was written in C# and did not install into Visual Studio. The only "integration" I was looking for was of the manual "External Tools" variety. I did not find a line counter that met these criteria, so I coded one up.

Directions

Simply unzip and run the executable. Select the directory where the source files reside (all subdirectories will be searched). Click the "Go" button to start the counting process. Only files with a ".cs" extension will be considered.

The goal for this counter was simplicity. In other words, just count the lines of code in the project. I didn't care about comment-to-source ratios or how much white space had been used - after all, we already know our source is pristine, right? We just need to find out how much of this wonderful stuff we've got. ;) In the pursuit of not driving myself totally nuts with this thing, I did put in two features. One, the application remembers the last directory selected (if it still exists). And two, the size and location of the form is restored (if the SystemInformation.WorkingArea is large enough to accommodate the previous settings).

What exactly is a line of code?

I'm glad you asked. Remember, this counter is simple. If a source code line trims down to nothing, it doesn't count. If, after being trimmed down, a line starts with #region, #endregion, or //, then it doesn't count. Lines which start with source code and end with a comment do count. For example, if a /* style comment starts halfway through a line, that line is counted. All subsequent lines up to the end comment */ are not counted. XML style comments also do not count. Now, can you defeat these little schemes and get some of your comments counted? Sure. In fact, you can count every line in the file as source if you like. What better way to get your LOC rating up to 5,000 a day, eh? In order to change the line counting behavior, we simply replace the brain of the counter.

Brain Surgery

Let's not get all stilted here and call it a parser, String.IndexOf(); and String.StartsWith(); do not make a parser. However, the counter definitely has to do something (if only a little something) to figure out whether or not a given line is really source. This all important function is the responsibility of the Brain class. In the constructor of the LineCounter class, you'll find this bit of code:

CodeFileModel _Model = new CodeFileModel();

Brain simpleton = new Simpleton();

_Model.Brain = simpleton;

Now the implementation of Simpleton, is, well, simple. He enforces all of the rules outlined above with slavish devotion. We can change his behavior though, by setting Boolean properties that represent the type of line we want to include in the count:

simpleton.CountBlankLines = true;
simpleton.CountRegions = true;
simpleton.CountSingleLineComments = true;
simpleton.CountMultiLineComments = true;
simpleton.CountXMLSummaries = true;

With this configuration, Simpleton would count all of the lines as source. Alternatively, you could implement a whole new Brain descendant. Brain contains only one function IsSource which takes a single line as a parameter and returns a Boolean indicating whether or not the line should be counted.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Tom Ollar
CEO Sagerion, LLC
United States United States
Member
I read About Face by Alan Cooper in 1995 and immediately recognized it as a founding document for the future of software. I also recognized we had a long, long way to go - and yes, even with the advent of iOS, we are still not there yet.
 
At my company, Sagerion (say-jair-ee-on), we can take a look at your planned or existing software and suggest ways of making it better - lots better. We can develop down-to-the-pixel blueprints showing exactly what our suggestions mean. We can help manage on-going development to make sure the top-notch user-experience we've suggested really does get built. Now, honestly, how often have you ever seen all those things happen?
 
You may or may not already have great development going on - but what does that matter if you don't have great design driving it?
 
Feel free to contact me at tom@sagerion.com, I would love to hear about your next ground-breaking project.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSmall bug in projectmemberJohniak8 Apr '12 - 22:43 
You should use attribute:
[STAThread]
before Main.
GeneralIt hangs on "select folder"membermtthwbrnd1 Apr '11 - 0:03 
Task manager shows "Not Responding" when I click select folder.
GeneralRe: It hangs on "select folder"membertomollar5 Apr '11 - 2:04 
Try this line above the Main method in starter:
 
[System.STAThread]
 
Cheers!
 
Tom
GeneralCome, it's just a simple work, but make it complicatedmemberSVGamer14 Oct '10 - 9:40 
as subject
GeneralMy vote of 2memberkuratowski11 Mar '10 - 2:59 
The sample exe doesn't run
GeneralCode Downloaded and compiled - but Folder Dialog does not workmembermitchellm4411 Mar '08 - 4:27 
I downloaded and compiled this and when you click on the Search folders button,
a dialog box shows up but with no ability to navigate to anywhere -- This
might be a starting point for something, however I got the idea the
source code was complete.
GeneralRe: Code Downloaded and compiled - but Folder Dialog does not workmemberJonathan C Dickinson28 May '08 - 0:54 
Try adding the [STAThread] attribute to static void main.
GeneralA small bug fixmemberSenaka Fernando22 Jun '07 - 7:50 
This application needs just a small correction so that it would not recognize lines that start with spaces instead of tabs as code.
 
In the Simpleton.cs replace aLine = aLine.Replace("\t", String.Empty); with aLine = aLine.Replace("\t", String.Empty).Trim(); so that the spaces are trimmed on each line.
 
This is great stuff...Smile | :)
 
Best Wishes
 
Senaka Fernando
QuestionBlix ???memberTony Tam1 Jan '07 - 19:22 
It is great. But what is blix ?
AnswerRe: Blix ???memberespeholt_jr24 Mar '07 - 12:16 
It is some custom designed UI controls so has nothing to do with the counting.
 
Best regards
Lasse Espeholt
GeneralRe: Blix ???memberthe_hijacker6 May '11 - 1:15 
Where can find this custom UI. It looks like original homepage blix.net is not longer working.
 
Can you please share the files for it if you still have them?
 
Thank you.
GeneralVS2005memberNZ Programmer10 Sep '06 - 2:27 
I had to add [STAThreadAttribute()] before void Main to make it work under VS2005 and .NET 2.0
GeneralGreatmemberPiotr Nogalski29 Jan '06 - 22:57 
Run the demo application and it worked fine! Good job Smile | :)

GeneralExceptionmemberBrian Pead25 Jul '05 - 9:23 
The app looks good, but I got an exception while scrolling through the file names when running it on a big project (5,175 cs files). I haven't tried debugging yet, but thought you may have some ideas as to the problem. Here's the exception text:
 
************** Exception Text **************
System.ArgumentException: Invalid parameter used.
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit)
at blix.Blaster.BlastOffscreenToForm(Rectangle aFormBounds)
at blix.ScrollBlaster.Paint(Rectangle aExposedScrollArea, Pan aPan, ControlCollection aControls)
at blix.ListViewScrollRefresher.ScrollUp(Int32 aDelta)
at blix.ScrollRefresher.VerticalScrollCycleScrollHandler(Int32 aDelta, Int32 aIncrementalDelta)
at blix.VerticalScrollBar.blix.IScroll.Scroll(Int32 aDelta)
at blix.VerticalScrollThumb.DragCycleDragHandler(Point aDragDelta)
at blix.DragCycle.TriggerDrag(Point aDelta)
at blix.Dragger.MouseMove()
at blix.DragTunnel.blix.IDragTunnel.MouseMove()
at blix.FormOverlayHub.MouseMove()
at blix.ControlSystem.MouseMove()
at blix.FormAdapter.OnMouseMove(MouseEventArgs ea)
at System.Windows.Forms.Control.WmMouseMove(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at blix.FormAdapter.ProcessMessage(Message& aMessage)
at blix.MoveMode.ProcessMessage(Message& aMessage)
at blix.SLIME.ProcessMessage(Message& aMessage)
at blix.FormAdapter.WndProc(Message& aMessage)
at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
 

************** Loaded Assemblies **************
mscorlib
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.2032
CodeBase: file:///c:/winnt/microsoft.net/framework/v1.1.4322/mscorlib.dll
----------------------------------------
CSharpLineCounter
Assembly Version: 0.0.0.0
Win32 Version: 0.0.0.0
CodeBase: file:///W:/Visual%20Studio%20Projects/CSharpLineCounter/CSharpLineCounter/bin/Release/CSharpLineCounter.exe
----------------------------------------
blix
Assembly Version: 1.0.0.1
Win32 Version: 1.0.0.1
CodeBase: file:///W:/Visual%20Studio%20Projects/CSharpLineCounter/CSharpLineCounter/bin/Release/blix.DLL
----------------------------------------
System.Windows.Forms
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.2032
CodeBase: file:///c:/winnt/assembly/gac/system.windows.forms/1.0.5000.0__b77a5c561934e089/system.windows.forms.dll
----------------------------------------
System.Drawing
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.2032
CodeBase: file:///c:/winnt/assembly/gac/system.drawing/1.0.5000.0__b03f5f7f11d50a3a/system.drawing.dll
----------------------------------------
System
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.2032
CodeBase: file:///c:/winnt/assembly/gac/system/1.0.5000.0__b77a5c561934e089/system.dll
----------------------------------------
System.Runtime.Serialization.Formatters.Soap
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.2032
CodeBase: file:///c:/winnt/assembly/gac/system.runtime.serialization.formatters.soap/1.0.5000.0__b03f5f7f11d50a3a/system.runtime.serialization.formatters.soap.dll
----------------------------------------
System.Xml
Assembly Version: 1.0.5000.0
Win32 Version: 1.1.4322.2032
CodeBase: file:///c:/winnt/assembly/gac/system.xml/1.0.5000.0__b77a5c561934e089/system.xml.dll
----------------------------------------
 
Thanks.
 

GeneralFeedback Welcome!memberthe Coding Samurai24 Jan '05 - 6:23 
If you have any questions/problems/issues with this utility, feel free to ask a question here or e-mail me directly. I'd be happy to help!
 
Tom Ollar
the Coding Samurai
GeneralRe: Feedback Welcome!sitebuilderUwe Keim24 Jan '05 - 19:07 
Regarding your question in the lounge [^], I personally would say that I like

  • that your article follows Marc's guidelines
  • has no horizontal scrollbar Smile | :) (I really do like this fact!)
  • has a good "texture" (what means to me the mixture of orange source code, literal article text and screenshots)
I would critisize

  • That your screenshot's controls have no WinXP style and look amateurish, a little bit
  • Your article is rather short (just by scanning over it). I think even a simple topic should cover at least 2-3 pages.
All personal opinions, just my feedback, since you asked Big Grin | :-D .
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

GeneralRe: Feedback Welcome!memberTom Ollar25 Jan '05 - 3:48 
Uwe,
 
Thank you!
 
I really appreciate the feedback!
 
Tom Ollar
blix: more native than native

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 24 Jan 2005
Article Copyright 2005 by Tom Ollar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid