using = <type> directive

  • Thread starter Thread starter Dylan Nicholson
  • Start date Start date
D

Dylan Nicholson

Can someone confirm that a) is illegal, and b) the solution?

a)

namespace Test
{
struct MyStruct
{
int a;
int b;
}
using MyQueue = System.Collections.Generic.Queue<MyStruct>;

class MyClass
{
MyQueue q = new MyQueue();
}
}

b)

namespace Test
{
struct MyStruct
{
int a;
int b;
}
}

namespace Test
{
using MyQueue = System.Collections.Generic.Queue<MyStruct>;

class MyClass
{
MyQueue q = new MyQueue();
}
}

If I'm right, anyone else agree that this seems just a little silly?
 
Well the compiler is verifying this for you. What don't you believe
about the compiler. It's error message for a) is very specific about what
the issue is, and how to resolve it.

As for it being silly, no, I don't think so, since I think it would be
confusing to be able to have those defined arbitrarily all over the place.
It would make the code difficult to follow, IMO.
 
Can someone confirm that a) is illegal, and b) the solution?

Well, you could have used, instead of b), this:

namespace Test
{
using MyQueue = System.Collections.Generic.Queue<MyStruct>;

struct MyStruct
{
int a;
int b;
}

class MyClass
{
MyQueue q = new MyQueue();
}
}
[...]
If I'm right, anyone else agree that this seems just a little silly?

The compiler simply requires that the "using" directive come first. It's
about the only "pre-processor"-like thing C# supports, and I wouldn't use
the word "silly" to describe the requirement that the directive come
before any code the compiler will be compiling.

YMMV.

Pete
 
Well, you could have used, instead of b), this:

namespace Test
{
using MyQueue = System.Collections.Generic.Queue<MyStruct>;

struct MyStruct
{
int a;
int b;
}

class MyClass
{
MyQueue q = new MyQueue();
}

}


Ah, well, I thought I'd tried that, and because it put a squiggly line
under "MyStruct" in the using directive when I typed it, I assumed it
wasn't legal. But you're right, this is fine, and not really all that
silly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top