Use of the using keyword in C# - 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.

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.

Tool for 'Flattening' (simplifying) C# Source

I need to provide a copy of the source code to a third party, but given it's a nifty extensible framework that could be easily repurposed, I'd rather provide a less OO version (a 'procedural' version for want of a better term) that would allow minor tweaks to values etc but not reimplementation using the full flexibility of how it is currently structured.
The code makes use of the usual stuff: classes, constructors, etc. Is there a tool or method for 'simplifying' this into what is still the 'source' but using only plain variables etc.
For example, if I had a class instance 'myclass' which initialised this.blah in the constructor, the same could be done with a variable called myclass_blah which would then be manipulated in a more 'flat' way. I realise some things like polymorphism would probably not be possible in such a situation. Perhaps an obfuscator, set to a 'super mild' setting would achieve it?
Thanks
My experience with nifty extensible frameworks has been that most shops have their own nifty extensible frameworks (usually more than one) and are not likely to steal them from vendor-provided source code. If you are under obligation to provide source code (due to some business relationship), then, at least in my mind, there's an ethical obligation to provide the actual source code, in a maintainable form. How you protect the source code is a legal matter and I can't offer legal advice, but really you should be including some license with your release and dealing with clients who are not going to outright steal your IP (assuming it's actually yours under the terms you're developing it.)
As had already been said, if this is a requirement based on restrictions of contracts then don't do it. In short, providing a version of the source that differs from what they're actually running becomes a liability and I doubt that it is one that your company should be willing to take. Proving that the code provided matches the code they are running is simple. This is also true if you're trying to avoid license restrictions of libraries your application uses (e.g. GPL).
If that isn't the case then why not provide a limited version of your extensibility framework that only works with internal types and statically compile any required extensions in your application? This will allow the application to continue to function as what they currently run while remaining maintainable without giving up your sacred framework. I've never done it myself but this sounds like something ILMerge could help with.
If you don't want to give out framework - just don't. Provide only source you think is required. Otherwise most likely you'll need to either support both versions in the future OR never work/interact with these people (and people they know) again.
Don't forget that non-obfuscated .Net assemblies have IL in easily de-compilable form. It is often easier to use ILSpy/Reflector to read someone else code than looking at sources.
If the reason to provide code is some sort of inspection (even simply looking at the code) you'd better have semi-decent code. I would seriously consider throwing away tool if its code looks written in FORTRAN-style using C# ( http://www.nikhef.nl/~templon/fortran/fortran_style ).
Side note: I believe "nifty extensible frameworks" are one of the roots of "not invented here" syndrome - I'd be more worried about comments on the framework (like "this code is ##### because it does not use YYY pattern and spacing is wrong") than reuse.

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

Does using namespaces affect performance or compile time?

If I put all classes of a project in the same namespace all classes are available everywhere in the project. But if I use different namespaces not all classes are available everywhere. I get a restriction.
Does using namespaces affect the compile time somehow? Since the compiler has less classes in each namespace and not all namespaces are used all the time he may have a little less trouble finding the right classes.
Will using namespaces affect the applications performance?
It won't affect the execution-time performance.
It may affect the compile-time performance, but I doubt that it would be significant at all, and I wouldn't even like to predict which way it will affect it. (Do you have an issue with long compile times? If so, you may want to try it and then measure the difference... otherwise you really won't know the effect. If you don't have a problem, it doesn't really matter.)
I'm quite sure, that putting classes in namespaces does not effect the compile time significantly.
But beware, that you might lose your logical project-structure, if you put every class into the same namespace.
I (and the Resharper) suggest to use namespaces that correspond with the file location (which corresponds with the project structure).
You should use namespaces according to your logic and ease of human readability and not for performance issues.

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

Categories