Question

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.

Was it helpful?

Solution

One of the reasons this feature is in place is to emulate Visual Basic 6.0's GlobalMultiUse Option for Instancing. Visual Basic 6.0 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.

Every time you call a subroutine or function on a class with the GlobalMultiUse Instancing, Visual Basic 6.0 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.

OTHER TIPS

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.

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.

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

wait, wait, wait....

I found just this morning that we could derived all the objects (class-s) inside any class that need their references using this method / function;

Protected Overrides Sub Finalize()
    MyBase.Finalize()
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top