Luke Lengl
Luke Lengl

Reputation: 110

Declaring an object without using the namespace of the class

I have a class library project named MyWidget, with the only class being named MyWidget.

In another project, I've added a reference to my class library, and in my new class, I've tried typing in

Imports MyWidget

and

Imports MyWidget.MyWidget

However, later in my class when I try to create a new reference, Visual Studio is not allowing me to type in this:

Private widget As MyWidget

However, Visual Studio is giving me a "Type Expected." error and forcing me to also include the namespace, like so:

Private widget As MyWidget.MyWidget

I read the MSDN documentation regarding the Imports statement. I should be able to leave off the namespace when declaring the object because I have the imports statement at the top of the program. I've tested this with standard namespaces, and it works fine, but when I try it out with my class, it doesn't.

Am I missing something in the MyWidget class that will allow me to leave off the namespace when declaring the object?

I also tried renaming the namespace to MyClasses, thinking maybe that Visual Studio was getting the namespace confused with the class. However, even with

Imports MyClasses.MyWidget

I still get an error when trying to define a MyWidget object without the MyClasses Namespace.

Upvotes: 2

Views: 691

Answers (2)

Luke Lengl
Luke Lengl

Reputation: 110

It appears that the issue was the namespace and the class having the same name. After changing the namespace to MyClasses and the class to MyWidget, the following statements worked:

Imports MyClasses

...

Private widget as MyWidget

Upvotes: 1

NoAlias
NoAlias

Reputation: 9193

Since the Namespace and Class have the same name the compiler gets confused when you try to instantiate MyWidget, despite the Imports statement. Just because there is an Imports statement, doesn't mean you can't fully quanlify a type (even if you have Imports System.IO.File, you can still call System.IO.File.WriteAllText), thus the confusion on the compilers end. An alternative would be to use an Alias.

Imports AWidget = MyWidget.MyWidget

Then..

Dim objWidget As New AWidget

Upvotes: 5

Related Questions