c# using declarations - more = good or bad? - c#

edit typos
Hi,
This is possibly a moronic question, but if it helps me follow best practice I don't care :P
Say I want to use classes & methods within the System.Data namespace... and also the System.Data.SqlClient namespace.
Is it better to pull both into play or just the parent, ie...
using System.Data
using System.Data.SqlClient
or just...
using System.Data
More importantly I guess, does it have ANY effect on the application - or is it just a matter of preference (declaring both the parent and child keeps the rest of the code neat and tidy, but is that at the detriment of the application's speed because its pulling in the whole parent namespace AND then a child?)
Hope thats not too much waffle

It doesn't make any difference to the compiled code.
Personally I like to only have the ones that I'm using (no pun intended) but if you want to have 100 of them, it may slow down the compiler a smidge, but it won't change the compiled code (assuming there are no naming collisions, of course).
It's just a compile-time way of letting you write Z when you're talking about X.Y.Z... the compiler works out what you mean, and after that it's identical.
If you're going to use types from two different namespaces (and the hierarchy is largely illusional here) I would have both using directives, personally.

Click Organize->Remove Usings and Visual Studio will tell you the correct answer.

Firstly, it has no effect on the application. You can prove this by looking at the CIL code generated by the compiler. All types are declared in CIL with their full canonical names.
Importing namespaces is just syntactical sugar to help you write shorter code. In some cases, perhaps where you have a very large code file and are only referring to a type from a specific namespace a single time, you might choose not to import the namespace and instead use the fully-qualified name so it's clear to the developer where the type comes from. Still, though, it makes no difference.

Express what you mean and aim for concise, clear code - that's all that matters here. This has no effect on the application, just on you, your colleagues and your future workers brains.

Use whatever happens when write your type name and press Ctrl + .,Enter in VS.

Related

Why "using namespace" directive is accepted coding practice in C#?

I am just curious to know why "using namespace" directive is acceptable in C#, though in C++ it is not. I am aware that C++ and C# are different, but my guess is C++ and C# come almost from same family, and should be using the same ideas for namespace resolution. C++ and C# both have an alias keyword to get around the namespace clash.
Can anybody point me, what I am not reading between lines in C# that makes it acceptable to use "using namespace" directive, and avoid the problems that C++ cannot.
In C++, if you write using namespace in a header, then it will be in effect for anyone who includes that header. This makes it pretty much unusable in headers. At that point, you might as well avoid it (at global scope) in .cpp files as well, if only for the sake of consistency, and to make moving implementations between .h and .cpp easier.
(note that locally scoped using namespace - i.e. within a function - are generally considered fine; it's just that they don't help with verbosity much)
In C#, there is nothing like #include, and the scope of a using directive will never span beyond a single .cs file. So it's pretty much safe to use everywhere.
The other reason is the design of the standard library. In C++, you just have std (well, now also a few more underneath it, but they are rarely used). In C#, you have gems such as System.Collections.Generic, which is extremely verbose for something that's used very commonly. It's just much more painful to avoid using in C# than it is in C++.
To sum it up, while C# and C++ do share some common design, on the matter of code modularity (I'd assign headers, modules, namespaces all to that group), their design is very different.
For me, it comes down to the support tools. Intellisense, the quick class lookup (F1 key), and refactoring options of Visual Studio give the needed reference lookup functionality.
Also, C# has every method within a class--there are no namespace level functions.
In general a difference of C# and C++ is how compilation units are handled and specified.
C++ uses header files to publish class declarations, and needs a compilation unit where this class is implemented (defined). A using namespace <xxx> statement in header files is strongly discouraged practice for C++, because this can easily lead to namespace clashes and ambiguities when included from some client code. In your class declaration you should explicitly state what you want from other namespaces (including std).
C# has single compilation units which eases use of using namespace <xxx> statements a bit. Nevertheless I'd prefer aliasing imported namespaces, if you want to avoid tedious typing. Placing using statements in a .cs file might cause ambiguous definitions as well.
While I completely agree with others that using namespaces should not be done in headers, I think banning them in cpp files is shortsighted. If you try to adhere to organizing declarations into namespaces ‘nicely’, but then ban the usage of ‘using namespace’ altogether, the path of least resistance for coders becomes the under use of namespaces.
For instance, in the above post by Pavel Minaev, he rightfully points out the namespace difference between a common C++ namespace, ‘std’, and a C# namespace, ‘System.Collections.Generic’. If you stop to think of why they are this way, a clear answer IMO is that C++ culture frowns on using namespace, while C# does not, so in C# you accept more verbose namespaces because they are not inherently painful to use. I believe namespace organization in C# is much better than C++ largely because of this cultural difference, and better class organization and general readability are not trivial things.
To put a different way, think about what would happen to people’s file organization habits if an application required them to type fully qualified paths to load a file. They’d more likely just shove everything into a root folder to avoid the typing, not a good way to promote quality organization.
While certainly not as clean as C#’s using directive, using namespace in cpp files is an overall win.
Unless you're a language purist, it saves time and makes coding easier. Unless you're dealing with complicated systems of namespaces, it's perfectly acceptable.

Should I use System.Guid.NewGuid() or using System and then Guid.NewGuid()?

When should I use full name, Sytem.Guid.NewGuid();? Should I always use using System; and then Guid.NewGuid(); for all cases?
you should use the later, i.e. include namespace first. The advantage of it is by only seeing the using statements, you will be well aware that which libraries are used in this file.
I think it will make more sense to use fully qualified name i.e. Sytem.Guid.NewGuid() if you have duplicate names at some level of class/namespace hierarchy which you want to avoid by explicitly telling the full name.
As System is pretty much unique namespace you should go for Guid.NewGuid()
I'd say consistency is more important than which alternative you choose. Personally I tend to always specify using directives and keep them sorted alphabetically, so it's really immediate to see what is or isn't there. Then in my code I always use unqualified names, except when I need to disambiguate between classes with the same name.
I personally don't like this long identifiers. The code is very hard to read if you have a lot of them.
However, when there are ambiguities between type names, the fully qualified version resolves this. I personally only use them when I have to, due to namespace conflicts. And also in this case I like more to declare a namespace aliase. This makes the code much more readable.
Anyway, for the compiled app, it makes no difference, the compiled code is the same.
What I also have encountered, that they were unpractical for some mannual refactoring action, but maybe the opposite may also be true, I don't remember the exact case...
Doesn't really make a difference, I think. 'Using' is more useful when coding, but when compiling to IL, all classes get compiled to their full name.
Namespaces are a compile-time only feature of C# that allow you to save time during development. The using directives are utilized by the compiler to look up shorthand Type names in your code.
Basically each time the compiler encounters a type name in your code that it does not know it takes each using directive and prepends it to the type's name and sees if that fully qualified name resolves.
Once you application is compiled the namespaces and the using directives are gone as the IL does not need them.
To answer your question it really doesnt matter.. if you are using it often in a single file then import it else use the fully qualified namespace

Using Statements vs Namespace path? C#

I recently stopped using using-statements and instead use the full namespace path of any .net object that I call.
Example:
using System;
namespace QuizViewer
{
class Class1
{
Console.WriteLine("Hello World!");
}
}
This is what I do now.
namespace QuizViewer
{
class Class1
{
System.Console.WriteLine("Hello World!");
}
}
Before you ask why I do this, I am using this style so that I can see exactly where my objects are coming from and it's easier when using the different Timer objects and other objects with similar names.
Is there any performance increase or decrease in this style of programming?
There is zero performance difference because the compiler ALWAYS puts in the full name - using is only a hint for the compiler, the runtime doesn't know or support that.
However, once you memorize where the objects come from you will look at this as silly and verbose. There is just so much noise and people just know that Path is from System.IO, Console is in System and StringBuilder is in System.Text.
One downside of your approach: Without using, no extension methods outside of the current namespace. Have fun writing System.Linq.Enumerable.Where(inputSequence,...) instead of just inputSequence.Where(...) :)
Short answer no: it is the same code that is compiled.
I think that this style result in a programmer performance decrease :). I use the using statement and usually it is clear from code to which namespace the class belong. If not, press F12.
Just my 2c.
There's no performance impact; it's mostly a stylistic choice. I find that using using statements reduces the clutter. Plus, with Intellisense, it's easy enough to see the fully qualified namespace.
The only performance hit, is the hit you take to type it all out, and with you or others reading it.
Using statements are to help readability, not really for performance.
If you disassemble both of this pieces of code and look at IL code, you'll find that compiler always references all the types by it's full names. That is absolutely identical ways to operating types.

Problem with recurring namespace-names

I have a class named AppVisum.Membership.Views.AppVisum.Membership.Controllers.Membership._Page_Views_AppVisum_Membership_Controllers_Membership_Validate_cshtml. Yeah, I know it is hidious, but I rather think it has to be named that, and as for the namespaces, those are unnecessary, but the class is generated by a tool, and the folder needs to be named AppVisum.Membership.Controllers.Membership, so I don't know if I can change the namespaces. However, hideous names isn't the real problem, the main issue is getting to the class AppVisum.Sys.AppSys. The ide tells me that it can't find AppVisum.Membership.Views.AppVisum.Sys.AppSys, so how can I tell it that I want the root one?
[Edit]
Sorry I wasn't specific enough as I thought this would be a simple problem to solve. The global:: would've worked perfectly if this had been a normal .cs file, however, it's a razor-file and razor don't quite like #using global::AppVisum.Sys (that just translates to using global, which doesn't make any sense). I've found 2 possible solutions, the first is to simply change the rule that search for files to search for folders with _ instead of .. Then I'd get paths like AppVisum.Membership.Views.AppVisum_Membership_Controllers_Membership._Page_Views_AppVisum_Membership_Controllers_Membership_Validate_cshtml. This would probably work just fine, and unless someone comes up with a better alternative I think I'm going for that. Another option is to rewrite the custom-tool that generates the classes (it's opensource, so I think I should be able to do that too fairly simply). Hope that clarifies things.
Add the global:: prefix to the namespace.
try:
using Sys = AppVisum.Sys;
or:
using AppSys = AppVisum.Sys.AppSys;
Basically, you can reduce ambiguity by aliasing types and namespaces in your using directives. (And the aliases don't need to be the same as the type/namespace names, they just are in my examples.)
As SLaks mentions in a comment, you should basically fix your project's default namespace - either that, or avoid creating the folder hierarchy. You've tagged this question with C#, but is your generated code actually in VB? While the VB compiler prepends the project's namespace when compiling, I don't believe the C# compiler does, so I'm surprised you're getting this namespace to be honest.
I disagree with your claim that "hideous names isn't the real problem" - I'd say it is the real problem, and making it hard to get at a particular namespace is one consequence of the problem. Fix the real problem (the bad namespaces) and the rest will go away. Using global:: etc is just a workaround, and one that you'll need to apply all over the place. It would be better to sort this out once and for all.
Basically if you can tell us more about how you've got into this situation, we're more likely to be able to help you get out of it.
maybe you can simplify by adding an using alias :
using AV = AppVisum.Membership.Views.AppVisum;
and in the code :
var s = new AV.Sys.AppSys();

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.
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.
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.
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.

Categories