Should I use Imports or not?

Viewed 66

To avoid having unnecessary code in my program, I am wondering which choice should I use:

  1. Use the statement like this Imports System.Threading and then use the code Dim myTimer As Timer
  2. Do not use the statement Imports System.Threading at all, but use a full declaration like this: Dim myTimer As System.Threading.Timer

Both choices give the desired result, but I want to avoid adding all extra code from System.Threading that I do not need.

The question came to my mind when I saw the answer to the question here: How to correctly terminate an application? Here the user wrote …Threading.Timer(…, but didn't use Threading on the Timeout.Infinite.

Since I am using System.Threading in only one point in my code, which choice would be better?

Thank you.

2 Answers

You don't "add all extra code from System.Threading" if you use Imports. You just tell the compiler that you want to use that namespace, so you avoid always using the fully qualified namespace.

As a rule of thumb: use Imports whenever you need it at least once. Fully qualified namespaces don't make your code more readable, it's also harder to see what you use in this class if you omit the Imports.

You can use Code Cleanup On Save to ensure that unused Imports are removed from your code when you save the file. But again, this is just removing redundant code, it will not improve performance or whatever.

Another option (that I favour) is to use Add Reference and/or Import Namespace on the project's References tab rather than use Imports or fully-qualified names. Unless it's just a single instance or two, in which case I'll fully-qualify to tell me that I don't use this reference/namespace a lot in my code. It's just a preference. (Or should I say a "reference preference"? Perhaps not.)

Related