When you reference certain methods, you can either use using
or explicitly type in the entire namespace. Are there any speed advantages of using one method over the other, or is it simply there to make typing out the entire namespace easier? thanks
views:
124answers:
3
+6
A:
There is no difference at runtime.
In the .NET meta-data, a type is always represented using a full name that includes the namespace, so the using
directive known from C# will disappear when a program is compiled.
There are some subtle aspects (at compile time) when it comes to writing the using
inside or outside of a namespace
(see for example this question), but that's also only a compile-time issue.
Tomas Petricek
2010-10-12 01:47:02
Nitpick: it's the using *directive*, not the using *statement*.
dtb
2010-10-12 02:20:58
`using` statement is for disposing of an object which implements IDisposable so that it can be garbage collected.
JD
2010-10-12 03:53:40
Thanks for the correction, yes it is a directive :-)
Tomas Petricek
2010-10-12 09:54:46
+3
A:
It's purely a syntactic matter and is compiled to the same thing. Take a look at the IL produced by each.
Jon Hanna
2010-10-12 01:47:18
A:
Are we all forgetting about extension methods? They cannot be pulled into scope without a using
namespace directive, as far as I know.
James Dunne
2010-10-12 03:55:34
But that doesn't matter because extension methods do not exist in the metadata/IL level (unless you count ExtensionAttribute, but that's for the compiler, not the CLR).
siride
2010-10-12 04:04:33
The question is "does 'using' provide any advantages?" The answer is yes, you get extension methods in C# 3.0 and up - in addition to shortened identifiers in your code file. But no, there are no runtime advantages nor disadvantages.
James Dunne
2010-10-12 04:17:51
True, but in the text of the question it is specific in asking whether it has any advantages to the code rather than just being syntactic sugar. Since extension methods are also just syntactic sugar (albeit sugar that LINQ needs to make some medicine go down) they aren't relevant here; `someEnumerable.Count()` is no different to `System.Linq.Enumerable.Count(someEnumerable)` and so on.
Jon Hanna
2010-10-17 19:23:13