I got an error today while trying to do some formatting to existing code. Originally, the code had the using
directives declared outside the namespace:
using System.Collections.Generic;
namespace MyNamespace
{
using IntPair = KeyValuePair<int, int>;
}
When I tried to insert the using
directive inside the statement (to comply with StyleCop's rules), I got an error at the aliasing directive, and I had to fully qualify it:
namespace MyNamespace
{
using System.Collections.Generic;
//using IntPair = KeyValuePair<int, int>; // Error!
using IntPair = System.Collections.Generic.KeyValuePair<int, int>; // works
}
I wonder what difference there is between the two cases? Does the location of the (import-style) using
directive matter?
The using directive can appear: At the beginning of a source code file, before any namespace or type declarations.
A using directive provides access to all namespace qualifiers and the scope operator. This is accomplished by applying the using keyword to a namespace identifier.
The using directive allows you to abbreviate a type name by omitting the namespace portion of the name—such that just the type name can be specified for any type within the stated namespace.
C# preprocessor directives are the commands for the compiler that affects the compilation process. These commands specifies which sections of the code to compile or how to handle specific errors and warnings.
I used to think that it did not matter, but I always fully qualify using commands.
Edit: Checked the C# spec, section 9.4 says that:
The scope of a using-directive specifically does not include its peer using-directives. Thus, peer using-directives do not affect each other, and the order in which they are written is insignificant.
So if System.Collections.Generic and KeyValuePair are treated as peers then KeyValuePair is going to ignore System.Collections.Generic.
Yes, it does - to a small extent. There is an edge-case to do with scoping / local names, see Eric Lippert's blog.
For a concrete example (specific to alias usage):
using System;
using Foo = Bar;
public static class Bar {
public static void Test() { Console.WriteLine("outer"); }
}
namespace MyNamespace {
//using Foo = Bar;
public static class Bar {
public static void Test() { Console.WriteLine("inner"); }
}
static class Program {
static void Main() {
Foo.Test();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With