• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 357
  • Last Modified:

unused variables

I am writing a program to identify all the unused variables in the code...

how can i achieve that... becoz we cannot say the variable which is not repeated twice as unused
becoz the unused variable may be in comments...

so any idea... i am using c sharp
2 Solutions
If you plan to write such a program, you need to properly parse C# syntax, so that means your program will ignore comments and not be confused by variables in a comment.

So proper code analysis for this (this is data flow analysis) would involve what we call a du-chain (declaration - usage chain).
--Compute the line that the variable is declared
--Compute the lines where the variable is used

Unused variables will have a d but no u
Local variables that are used will have separate d-u lines
Public members, etc. may be used all over the place, and may be static, out of order, in other files. This will be your challenge.

Start with a proper C# parser.
How are you reading the files?  Streamreader?

Looking for multiple uses of the variable sounds like a good start.  When counting the times a variable is used, you'll have to ignore commented lines.  How you do that will depend on how you are reading the files.
About working with code, from my own experience :). mrjoltcola told already about analyzing separate lines. That's what I did. I read text into a list of strings, each line is a separate items. E.g., in this case you may check easily if a line, e.g., starts from comment mark "//" etc. Or if a variable name is after comment mark on this line.
About unused variables.
1. Line where variable is declared should not have assignments ("=" sign, I believe)
2. There is no assignment in the following code (in not commented out part)

It's not to hard to check if this variable is class level variable or a local method variable. In the later case you need to scan the method only while in the firs case you need to scan entire class from the declaration. For big classes it may be an issue (we have classes with up to 25000 lines - stupid but fact :))..

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now