30

By redundant stuff, I mean the namespaces, as I know they are necessary but if there are 10k of them, it doesn't add valuable info to the table.

Could this be done using Linq?

5
  • Perhaps if you can explain why you need this then a good solution can be provided.
    – Bernard
    Commented May 10, 2011 at 20:36
  • 16
    Wait... doesn't everyone get paid per line? Commented May 10, 2011 at 20:38
  • 1
    I want to compare 2 similar very large apps, and they are both good in functionality, but I want to know which one has the less code, like if one is half the size, then I think that's pretty good, because it does more than the first one.
    – Joan Venge
    Commented May 10, 2011 at 20:42
  • 3
    less code is not always better. To maintain clarity (simple KISS principle and hence easier support in longer run), it's always better to write more lines of clear and meaningful code. How about a code review? Probably that would give you more insight on 'good' code. Commented May 10, 2011 at 20:47
  • True but I have seen the code of both and I think the second one has nicer code, but I also feel their version might be less code because they have a better architecture.
    – Joan Venge
    Commented May 10, 2011 at 21:00

7 Answers 7

44

Visual studio will do this for you. Right click on your project and choose Calculate Code Metrics.

9
  • 1
    No reason if there a tool that does this but neither in vs 2010 nor in 2008, I saw this option when I right clicked on a project. Is it an extension?
    – Joan Venge
    Commented May 10, 2011 at 20:41
  • I have 2010 Ultimate and it shows up there. Not sure if it came as part of VS, Resharper or Productivity Power Tools which are all installed.
    – grenade
    Commented May 10, 2011 at 20:46
  • I only have pro version at work. I guess MS thinks if you use pro, you don't need this tool.
    – Joan Venge
    Commented May 10, 2011 at 20:58
  • I have VS Premium. It appears that VS Pro doesn't have this feature. Commented May 10, 2011 at 21:35
  • 2
    VS 2019 Community version has it as well. Its in all the versions now.
    – Herb F
    Commented Jun 18, 2020 at 19:41
37

No need to reinvent the wheel. Take a look at the Visual Studio Code Metrics PowerTool 11.0

Overview

The Code Metrics PowerTool is a command line utility that calculates code metrics for your managed code and saves them to an XML file. This tool enables teams to collect and report code metrics as part of their build process. The code metrics calculated are:

• Maintainability Index

• Cyclomatic Complexity

• Depth of Inheritance

• Class Coupling

• Lines Of Code (LOC)

I know you said you don't have Ultimate, so I just wanted to show you what you're missing.

Code Metrics in VS 2010 Ultimate

For everyone else, there's SourceMonitor Source Monitor

9
  • This still requires VS 2010 ultimate.
    – Joan Venge
    Commented May 10, 2011 at 20:59
  • 1
    The feature requires VS premium or higher. Commented May 10, 2011 at 21:36
  • 2
    of course it doesn't include empty lines and comments. --disclaimer: I am not speaking from a position of knowledge or insider opinion. I am just of the opinion that it's highly unlikely that some dude on impulse on SO has outsmarted a development team on a payroll in a fundamental design flaw.
    – grenade
    Commented May 10, 2011 at 23:13
  • 2
    FYI VS2015/2017 pro include the Code Metrics tool as a built in. Commented Jul 13, 2017 at 19:35
  • 1
    VS 2022 Community has this on a Solution Explorer project or solution right-click menu as Analyze and Code Cleanup -> Calculate Code Metrics. And it works on .NET Standard / .NET Core projects too. Commented Dec 17, 2022 at 14:57
4

From: http://rajputyh.blogspot.in/2014/02/counting-number-of-real-lines-in-your-c.html

private int CountNumberOfLinesInCSFilesOfDirectory(string dirPath)
{
    FileInfo[] csFiles = new DirectoryInfo(dirPath.Trim())
                                .GetFiles("*.cs", SearchOption.AllDirectories);

    int totalNumberOfLines = 0;
    Parallel.ForEach(csFiles, fo =>
    {
        Interlocked.Add(ref totalNumberOfLines, CountNumberOfLine(fo));
    });
    return totalNumberOfLines;
}

private int CountNumberOfLine(Object tc)
{
    FileInfo fo = (FileInfo)tc;
    int count = 0;
    int inComment = 0;
    using (StreamReader sr = fo.OpenText())
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            if (IsRealCode(line.Trim(), ref inComment))
                count++;
        }
    }
    return count;
}

private bool IsRealCode(string trimmed, ref int inComment)
{
    if (trimmed.StartsWith("/*") && trimmed.EndsWith("*/"))
        return false;
    else if (trimmed.StartsWith("/*"))
    {
        inComment++;
        return false;
    }
    else if (trimmed.EndsWith("*/"))
    {
        inComment--;
        return false;
    }

    return
           inComment == 0
        && !trimmed.StartsWith("//")
        && (trimmed.StartsWith("if")
            || trimmed.StartsWith("else if")
            || trimmed.StartsWith("using (")
            || trimmed.StartsWith("else  if")
            || trimmed.Contains(";")
            || trimmed.StartsWith("public") //method signature
            || trimmed.StartsWith("private") //method signature
            || trimmed.StartsWith("protected") //method signature
            );
}
  1. Comments of // and /* kind are ignored.
  2. A statement written in multiple line is considered single line.
  3. brackets are (i.e. '{') not considered lines.
  4. 'using namespace' line are ignored.
  5. Lines which are class name etc. are ignored.
1

I have no solid idea about them, but you can use Code Metrics Values to get some statistics about your solution, like code lines.

1

we have used the tfs cube to get the data about how many lines add/delete/change on our tfs. This one you can view from excel. But need to configure it properly. And I don't think it will exclude the comments and blank lines etc.

1
  • How did you do this? I'm trying to get change stats on our project like what git has (how much code was left from the previous version, how much was added...)
    – Ziv
    Commented Aug 21, 2013 at 9:28
1

Ctrl+Shift+f (Find in files) -> put ";" in the "Find what:"-textbox -> Press "Find All"-button.

This extremly simple method makes use of the fact, that any C# statement is terminated with a semicolon. And, at least I dont't use semicolons at any other place (e.g. in comments)...

3
  • 1
    if(true) is a line of code but doesn't end with ;
    – IEatBagels
    Commented Nov 1, 2018 at 19:38
  • Not to mention class Foo {, void Foo() {, IReadOnlyList<int> Foo {, etc.
    – Qwertie
    Commented Mar 12, 2020 at 1:53
  • That's correct, however the accuracy is not that far off and tends to be conservative (some false positives but no false negatives). While missing a few lines, the method gives good confidence, that at least this much true LOCs exist. And it is extremely simple.
    – Martin777
    Commented Mar 12, 2020 at 8:40
1

As mentioned above but in easy way

  1. from solution explorer right click your project.

  2. select "analyze and code cleanup".

  3. select calculate code metrics

then you will get all information such as all code lines

enter image description here

Not the answer you're looking for? Browse other questions tagged or ask your own question.