yeyeyerman
yeyeyerman

Reputation: 7941

Use of the using keyword in C#

In my background in C++ I was a supporter of using the scope resolution operator, for example

class Foo
{
    std::list<int>  m_list;
    ...
}

for external libraries, to keep clear which library you were using.

Now in C# I don't know if there's a rule of thumb or a best practice to know which packages should be included via the using keyword and which classes should be fully qualified. I suppose that this can be a subjetive issue, but would like to know the most extended practices.

Upvotes: 2

Views: 336

Answers (3)

ShuggyCoUk
ShuggyCoUk

Reputation: 36476

Tend towards whatever makes the code more readable and understandable.

If the name may be ambiguous and their is no common "most likely case" then fully/partially qualifying to make this clear can be sensible even if this increases verbosity.

If confusion exists but one candidate is far more likely then qualify only in those cases where you do not use the most common case. Common example is the use of System.Collection.X classes rather than the System.Collections.Generics versions (perhaps for back wards compatibility). In this case importing the generic namespace is fine and any non generic ones are fully qualified. This makes it clear where you are using legacy code.

If you will be dealing with multiple clashes and the resulting full qualification would make you code extremely unreadable then it may make sense to use aliases to separate them out but you should be pretty averse to doing this since it renders the resulting code easier to physically read but harder to conceptually understand. You have injected an element of inconsistency with the wider world. this makes code snippets within the class harder to understand in isolation.
If you must do this consider alias names which make it very clear that these are aliases as an indication to readers that they should look at the using statements for confirmation of the real types.

Upvotes: 1

Sam Harwell
Sam Harwell

Reputation: 100029

I think the saving grace in C# is the directives are fully constrained to the file you place them in. I use them whenever their use is clear for the code in the file and it helps readability of the code. Another team at my office doesn't use them at all - I think it's nuts but they came up with their own rules and are happy with them.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503859

I pretty much never fully qualify names - I always use using directives instead.

If I need to use two names which clash, I'll give both of them aliases:

using WinFormsTextBox = System.Windows.Forms.TextBox;
using WebFormsTextBox = System.Web.UI.WebControls.TextBox;

That rarely comes up though, in my experience.

I tend to make autogenerated code fully qualify everything though, just for simplicity and robustness.

Upvotes: 16

Related Questions