I was under review of team code. I observe they had used class ClassAby writing using AAA.BBB; at the upper portion of the class; also they have sometime used class ClassB by AAA.BBB.ClassB. There are two basic questions.
Is there any performance issue while using above scenario. What is recommended
When I declare namespace; are all classes get loaded of that namespace or not.
Please assist here. Thanks.
I'll answer these as best as I can, I don't have any sources on hand, just experience (maybe someone can help with that).
There is no performance issue with importing a namespace versus calling it directly. When the compiler runs through it, you can think of it as always being fully qualified in the end. The using statement for namespaces is more to assist the developer so they don't have to fully qualify it each time. In fact, for your ClassB example, it could be that there is a collision with multiple namespaces defining the same class name. For example, the Calendar class is both in System.Globalization and System.Web.UI, so you have to fully qualify one or the other when using them.
Generally, all code is compiled into an assembly by the project it's under. Referencing any code inside of the assembly will load all of the associated code. Note, however that the code isn't necessarily compiled for use by the JIT until it's actually called.
Namespaces are for organizing your code (while preventing name collisions). They have no bearing on performance at all.
Fully qualified names in code are distracting and noisy. I prefer to never have them. If there is a namespace conflict, a using alias can resolve that.
only for places where there is a conflict with there being two Class defined in different namespaces, and, even then, I'll still rather use a using to differentiate them:
using MyClassB=AAA.BBB.ClassB;
// :
var myClassB= new MyNS();
in terms of performance, you can see the answer here:
The using directive is only syntactic sugar that disappears during
compilation. Whether or not the namespace was included via using or
mentioned in a fully-qualified type name is totally irrelevant in the
resulting bytecode. Hence, there is no performance benefit at runtime
by using one or the other.
Related
McCarson.LearningToCode.Week(3);
Adding to give context to set experience expectations
I have seen developers import references on the code behind for very specific elements within a library as well as import references for the entire library itself irrelevant of whatever the needed element is. How much memory is conserved (if any) with the specific element needed being referenced for the page, to the point that, is it considered best practice to only import the needed element or is it a trivial concern? (I did see that it marginalizes room for error)
I researched MSDN, did not find the answer so asking here seems like a logical choice
Using/Importing is first a shorthand to avoid having to use fully qualified type names (Namespace + Classname).
There might be performance considerations too, but only while writing the code - not at runtime. Regardless how you write your code, the IL will still use a fully qualified typename. If you do not give a fully qualified name, Compiler and Intellisense kind of have to "guess" in wich used namespace the class you reference resides. Wich 95% of the cases works without any issues.
Using/Importing whole namespaces can have issues from a Ambiguity point of view. For example, there are at least 3 Namespaces with a "Timer" class. Each of them is a different type, with different bebavior and different Proeprties/Events.
If you using/import any two of those Namesapces, the classname "Timer" is no longer ambigious like "string" or "object" is. So all of a sudden, you have to use the fully qualified name for all Timer instances once again.
So in very rare circumstances, using/importing the whole namespace on a global level will cause you no end of issues. Hence it can be preferable to limit both the scope and the depth of a use/include directive.
It can be negligible to make using / importswhen there is no need but it can also harm performance (depends on your program and the referenced assembly size and hypersensitivity to performance) and its a bad programming habit.
the meaning of every using / imports statement is that the compiler will search properties / methods / classes etc within that assembly. also you must take into account the order of the using statements - the compiler will search according to the order of the using statements.
BTW - there is a small difference between VB.NET and C# - VB imports the major namespaces by default opposed to C#.
by saying major namespaces (.net framework 4.6):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
and as #Chillzy wrote in his comment VS will color
unnecessary imports in dark gray.
I've inherited an old .NET 2.0 C# system in work, currently sifting my way through an enormous code base. As I am a graduate I'm interested in why the existing developers did certain things, certain ways. One particular habit the previous developers had was, instead of importing the references at the top of the class like so -
using System.IO;
They did this continually throughout - (rather than importing the reference at the top).
System.IO.File.Exists();
Could anyone shed some light what the difference(s) is/are other than having to type more code? The system I'm working on is a business object orientated system (CSLA), and with no prior experience to this methodology, could someone recommend a good way to approach learning a system which I've inherited. I appreciate you can't see the system I've got but a bit of insight from someone experienced would be appreciated.
Regards.
It's just a style choice. Some people like to use the full names to know that local type names won't conflict with system types.
using statements are just a way to help the compiler find the referenced types at compile time, there is no difference at runtime between;
using System.IO;
File.Exists();
and
System.IO.File.Exists();
Could anyone shed some light what the difference(s) is/are other than
having to type more code?
It's a coding standard / style choice as Joachim says.
I personally use usings for most namespaces but will use fully qualified names if it makes the code clearer in a particular case. Such as to avoid ambiguity.
Further, I've seen some teams use usings for .NET types and fully qualified names for types that they have developed or very specific scarse types that the team is not always aware of. Using fully qualified names states that this type is rare and this is the namespace it's in so you don't have to go looking for it.
Could someone recommend a good way to approach learning a system which
I've inherited
Don't try to understand everything up front. Learn what you need to know when you need to know it (when you are making changes). Gather a high level understanding about where things are so you can find them quickly when you need to work on them.
I usually prefer using statements but there are places where it will be ambigious to use it.
Consider the following
namespace MyNamespace
{
public class File
{
public static bool Exists()
{
return false;
}
}
}
Then use
using System.IO;
using MyNamespace;
File.Exist();//this is now ambigious
In such cases you've to use System.IO.File.Exist();
Or
using System.IO;
using MyFile = MyNamespace.File;
File.Exist();//this is call is not ambigious since File means System.IO.File only
Other than these I don't find any reason to use full name rather than using statements
Personally, I like using the full name if I'm only using something in that namespace once or twice in the class. This way, it doesn't clutter up IntelliSense, and it helps me focus on the namespaces I actually care about in that particular class.
In C#, when you add a using directive for a namespace, it gives you access to all the types in that specific namespace. However, if the namespace has a lot of types and I only need one particular one, I often just use the fully qualified name thinking that I don't want to make available any unnecessary classes I know I am not going to use (especially if there are a lot of them in that namespace) for performance reasons. I was thinking that there has to be some impact to performance (no matter how minute) to make them available as opposed to not, but how much? (if there actually is one). And if so, would it then be bad practice to do this all over the place, because wouldn't it then start to accumulate to something noticable (performance wise)?
I did see the other SO post about using the using directive vs fully qualified names, but it wasn't in reference to performance.
The using directive is only syntactic sugar that disappears during compilation. Whether or not the namespace was included via using or mentioned in a fully-qualified type name is totally irrelevant in the resulting bytecode. Hence, there is no performance benefit at runtime by using one or the other.
There is no difference.
It might have a negligible (i.e. probably not measurable) impact/benefit on compiler performance (as in when running msbuild), but at runtime the IL explicitly knows the type that is intended, as it's baked in the code as a type handle. There is no 'searching' for types unless reflection is being used.
I must say, NO.
The compiler will produce the same IL code, so you don't have to worry about that.
that just depends.
Using the using directive helps you to write your code faster.
But, if you have e.g 2 namespaces where you use the using directive which both have methods which have the same name and also have the same signature you will get into trouble.
Using the full qualified reference can make your code more understandable.
I was wondering, what the purpose of Namespaces in C# and other programming languages is...
As far as I know, they are used for two things:
To structure the project into meaningful pieces
To distinguish classes with the same name
My Question is: Are there any other things to consider when using namespaces? Do they have an impact on performance or something like that?
As far as I know, they are used for two things:
• To structure the project into meaningful pieces
• To distinguish classes with the same name
That's basically it. I would add to your first point that namespaces provide structure larger than just that of the project, since namespaces may span projects and assemblies. I would add to your second point that the primary purpose of namespaces is to add structure to libraries so that it becomes easier to find stuff you need and avoid stuff you do not need. That is, namespaces are there as a convenience for the user of a library, not for the convenience of its creators.
A secondary purpose is to disambiguate name collisions. Name collisions are in practice quite rare. (If the primary purpose of namespaces was to disambiguate collisions then one imagines there would be a lot fewer namespaces in the base class libraries!)
Are there any other things to consider when using namespaces?
Yes. There are numerous aspects to correct usage of namespaces. For example:
violating standard naming conventions can cause confusion. In particular, do not name a class the same as its namespace! (See link below for details.)
using a namespace can bring extension methods into play that you didn't expect; be careful
where precisely the "using" directive goes can subtly change resolution rules in a world where there are name collisions; these situations are rare, but confusing when they arise
collisions often arise in contexts where machine-generated code is interacting with human-generated code; be careful in such situations, particularly if you are the one writing the code generator. Be very defensive; you don't know what crazy name collisions the person writing the human-generated half is going to create.
See my articles on this subject for more details:
http://blogs.msdn.com/b/ericlippert/archive/tags/namespaces/
And see also the Framework Design Guidelines for more thoughts on correct and incorrect conventions for namespace usage.
Do they have an impact on performance or something like that?
Almost never. Namespaces are a fiction of the C# language; the underlying type system does not have "namespaces". When you say
using System;
...
class MyException : Exception
...
there is no class named "Exception". The class name is "System.Exception" -- the name has a period in it. The CLR, reflection, and the C# language all conspire to make you believe that the class is named "Exception" and it is in the namespace "System", but really there is no such beast as a namespace once you get behind the scenes. It's just a convention that you can sometimes omit the "System." from the name "System.Exception".
According to MSDN a namespace has the following properties:
They organize large code projects.
They are delimited with the . operator.
The using directive means you do not need to specify the name of the namespace for every class.
The global namespace is the »root« namespace: global::System will always refer to the .NET Framework namespace System.
Secondly namespace has nothing to do with performance but if you have created your own namespace so you should follow the conventions across the project.
It doesn't affect performance. But for code readability, I would recommended remove unwanted using statements
Namespaces are a concept pulled from earlier technology, like XML. THe namespace gives context to your classes, allowing you to have say a CUstomer object in your domain and in your data code.
You can also use namespaces to alias, which still does the above, but allows shorter naming for the particular object.
domain.customer
versus
data.customer
You've touched upon the two main reasons. This is an old article from MSDN but it still applies: Namespace Naming Guidelines
In the Java world the naming practice is to reverse the domain name of the company who owns the product and include the product's name after that. So com.example.product might be a valid namespace, but you don't really see that in .NET so much.
Those are the big ones right there.
There aren't really performance benefits. At least, not directly. without namespaces framework would have to search the a lot more places to find the code you are trying to include - It would almost be like needing to load up the ENTIRE .NET framework for every project. Well, not really, but its close enough for this discussion.
I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces.
Example:
Project = Tully.Saps.Data
Folder = DataAccess/Interfaces
Namespace = Tully.Saps.Data.DataAccess.Interfaces
Folder = DataAccess/MbNetRepositories
Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories
Question:
Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?
Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
It is really up to you how you want to deal with it. If you are only going to be accessing a member of a namespace once or twice, then adding the "using" statement really doesn't do much for you.
If you are going to use it multiple times then reducing the namespace chain is probably going to make things easier to read.
You could always change the namespace so it doesn't add the new folder name if you are just looking to logically group files together, without creating a new namespace.
According to FXCop, and I agree:
Avoid namespaces with few types
A namespace should generally have more than five types.
also (and this applies to the "single namespace" suggestion -- which is almost the same to say as no namespace)
Declare types in namespaces
A type should be defined inside a namespace to avoid duplication.
Namespaces
.Namespaces help us to define the "scope" of a set of entities in our object model or our application. This makes them a software design decision not a folder structure decision. For example, in an MVC application it would make good sense to have Model/View/Controller folders and related namespaces. So, while it is possible, in some cases, that the folder structure will match the namespace pattern we decide to use in our development, it is not required and may not be what we desire. Each namespace should be a case-by-case decision
using statements
To define using statements for a namespace is a seperate decision based on how often the object in that namespace will be referred to in code and should not in any way affect our namespace creation practice.
Leave it. It's one great example of how your IDE is dictating your coding style.
Just because the tool (Visual Studio) you are using has decided that each folder needs a new Namespace doesn't mean you do.
I personally tend to leave my "Data" projects as a single Namespace. If I have a subfolder called "Model" I don't want those files in the Something.Data.Model Namespace, I want them in Something.Data.