Wednesday, October 20, 2010

Subtlety: When the location of using makes a difference for importing namespaces in C#.

Scenario
You've noticed C# code that imports namespaces with the 'using' keyword in two slightly different syntactic contexts.

  1. At the top of the source code file.
  2. In the body of another namespace.

Understand by Example
namespace My {
  public class C { }
}

namespace My.Foo {
  public class C { }
}

// C from My
namespace My.Bar {
  public class Bar { private C instance; } 
}

// C from My <-- this might be counter intuitive
using My.Foo;
namespace My.Bar {
  public class Bar { private C instance; }
}

// C from My.Foo
namespace My.Baz {
  using Foo;
  public class Baz { private C instance; }
}
EOF

No comments:

Post a Comment