Sunday, February 13, 2011

VB.NET Importing Classes

Edit: This was accidentally posted twice. Original: http://stackoverflow.com/questions/243900/vb-net-importing-classes

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.

  • By using the "HideModuleNameAttribute" you can call methods without identifying thier parent.

    Example:

    Public Class TestClassCaller
        Public Sub New()
            SomeMethod()
        End Sub
    
    End Class
    
    <HideModuleName()> _
        Public Module TestClass
        Public Sub SomeMethod()
    
        End Sub
    End Module
    
  • Imports only creates a reference to the class, it does not create an instance of it to use.

    The reason you see the function in your new class is that it's a shared function, which doesn't need the parent to have a created instance to use.

    Cheers!

    From thismat

0 comments:

Post a Comment