c# using declarations - more = good or bad?
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 appli开发者_运维问答cation - 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.
精彩评论