In C# we write using System.IO or any other namespace we want to use.
So is it a bad habit, does it affect performance or memory?
Or is it good to create wrapper classes for them and use it to avoid using the same namespace everywhere?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In .Net, the namespace is always an integral part of the name of each type.
However, if you had to specify the entire namespace each time you are declaring a certain type it would have caused tremendous repetition and noise in the code. This is what the using directive is for, it essentially folds all the prefixes into one place, making you specify the “last” section of a type. This can be done only in case there are no ambiguities.
The compiler however, doesn’t care about the above. So there exists a pre-compilation stage where each type declaration that relies on a
usingdirective gets its prefix back.So when you say:
What happens in pre-compilation is that the is appending the
Systemnamespace to eachStringdeclaration, like this:And only now the compiler really kicks in.
So about the performance, technically, it can effect performance of the build process. The more usings you have, the more matching needs to be done in the pre-compilation stage: so the compiler sees
String. WhatStringis that? Is itSystem.Stringor is itSomeOtherNamespace.String? What really happens is that the compiler appends each namespace it finds in using to the type declaration and checks whether such a type exists. If yes- great, if no- it trys the next namespace.So you see, in case you have many files with unused
usingdeclarations, the compiler necessarily does redundant work. In extreme cases, it can significantly degrade the performance of the build itself.In general, never hesitate Using something that you are using (no pun intended). But you should avoid declaring unnecessary
usingdirectives, not just because of the potential (unlikely) performance impact on the build duration but also because you want to keep your code as clean as possible.