Question

I often come across a class which has a single reference to another library and was wondering if its better to include the library or to reference the object by it's full name. Is one better then the other? Is one more of a standard then another?

For example using System.Windows.Messagebox:

Option A:

using System.Windows;

public class MyClass
{
    SomeMethod()
    {
        MessageBox.Show("Something");
    }
}

Option B:

public class MyClass
{
    SomeMethod()
    {
        System.Windows.MessageBox.Show("Something");
    }
}

If B, how many references do you need before you decide to add the entire library?

Was it helpful?

Solution

I would prefer 'Option A'. It clearly states, that this file indeed uses that library. And anybody new to the code won't be searching for signs of external references through the whole file. Don't know about such standards though, just reasoning.

OTHER TIPS

If it is indeed a single use, I tend to go with option B. However, the moment I notice more than a single use, it's normally better off as option A. Might be just me, but I don't really like polluting the default namespace with potentially a large number of identifiers, only one of which is ever used and only once.

This differs somewhat based on the size of the namespace named in the using directive; a large namespace, such as System.Windows, sees more scrutiny at my keyboard than, say, System.Collections.Generic. It also depends somewhat on the size of the source code file; in a small file, it's easier to have an overview of what adding a using clause might do. (Yes, I know that best would often be to refactor and break up into smaller classes and files, but sometimes it's not practical to do so inside the scope of a small task.)

My rule of thumb is that if I use a library a lot in a particular class file then I'll include it (it looks neater and saves typing). But if there's just a single reference to a rarely used class in my code then I may well reference it using the fully qualified name (that way it's obvious which namespace it is in).

Don't forget in Visual Studio you can collapse namespace definitions and also easily remove unused using statements, if you find you have a lot.

Option A clearly identifies your class' dependencies. If it has too many, you will notice that very easily.

Licensed under: CC-BY-SA with attribution
scroll top