tags:

views:

431

answers:

4

I've seen some code where a Class is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well?

TestClass.vb

public class TestClass
    public shared function Somefunc() as Boolean
     return true
    end function
end class

MainClass.vb

imports TestClass

public class MainClass
    public sub Main()
     Somefunc()
    end sub
end class

These files are in the App_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere.

+1  A: 

Actually, that function is available because it's a shared function. If you were to remove the shared modifier, you would still have to create an instance of the class to access it.

To achieve access to all variables and all functions within a class by default, you would want to inherit it.

To my knowledge importing a class is basically tying direct reference to it, not creating any sort of instance of it for you to use.

EDIT for clarity: The links are there are VB specific links, thus, explaining the functionality of this pertaining to VB.NET

thismat
+2  A: 

Yes, it's a Visual Basic language feature. While you can create aliases, using C#'s using statement, it doesn't appear that you can import a shared class into scope. To be honest, I've only ever used it once in a legacy project that had already used it. I see some value, but I'm afraid it may cause more harm than good for future maintainability of your code.

Bob King
+2  A: 

One of the reason feature is in place to emulate VB6's GlobalMultiUse Option for Instancing. Visual Basic 6 doesn't have the ability to make modules public across a DLL boundary. Instead you set the instancing property to GlobalMultiUse. It is used mainly for Utility Classes like a class that export a series of math functions.

What VB6 does is every time you call a subroutine or function on a class with the GlobalMultiUse Instancing it instantiates a class behind the scenes before calling the function.

It can be abused to generate global functions/variables with all the advantages and disadvantages.

RS Conley
+1  A: 

I use it whenever I am using the same library a lot of time. A good example is System.Math.

C# doesn't support this, which I find to be very annoying.

Jonathan Allen