C# Gotcha

I've just spent 10 minutes blankly staring at my screen trying to figure out why the heck an ultra simple piece of C# didn't work... Suppose you create the following and compile it into an assembly called JSL.HelloWorld.dll
namespace JSL.HelloWorld
{
    public class Example
    {
        //...
    }
}
And then you write a test for it...
namespace Tests.JSL.HelloWorld
{
    using JSL.HelloWorld;
    using NUnit.Framework;

    [TestFixture]
    public class ExampleTest
    {
        [Test]
        public void Eg()
        {
            Example puzzle = new Example();
            //...
        }
    }
}
Looks fine. Yet when you compile the test csc complains that "the type or namespace name 'Example' could not be found...". Ten minutes blank staring follows. The problem is there are two namespaces called JSL.HelloWorld. There's one that's global that contains the class called Example we're after. And there's another one inside the namespace called Tests (called Tests.JSL.HelloWorld). So the compiler tries to resolve Example in Tests.JSL.HelloWorld but not in JSL.HelloWorld. One solution is as follows:
namespace Tests.JSL.HelloWorld
{
    using global::JSL.HelloWorld;
    using NUnit.Framework;

    [TestFixture]
    public class ExampleTest
    {
        //...
    }
}

No comments:

Post a comment