Sunday, 22 August 2010

Equivalent of static classes is VB.Net

The closest thing in Visual Basic .Net to a C# static class is a Module (also known as a standard module). In C# a static class is described as follows:

“A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.” *

There is no direct equivalent in Visual Basic .Net but a Module has some properties similar to those of a static class:

  • Every module has exactly one instance and does not need to be created or assigned to a variable.
  • Modules do not support inheritance or implement interfaces.
  • A module is not a type - you cannot declare a programming element to have the data type of a module.
  • You can use Module only at namespace level.
  • The declaration context for a module must be a source file or namespace (not a class, structure, module, interface, procedure, or block).
  • You cannot nest a module within another module, or within any type.
  • A module has the same lifetime as your program.
  • All a module’s members are implicitly Shared. **

Example in C#:

static class SomeName
    public static string SomeMethod1() { return "Value 1"; }
    public static string SomeMethod2() { return "Value 2"; }

Equivalent in Visual Basic .Net:

Public Module SomeName
    Public Function SomeMethod1() As String
        Return "Value 1"
    End Function
    Public Function SomeMethod2() As String
        Return "Value 2"
    End Function
End Module

* Static Classes and Static Class Members (C# Programming Guide) 
** Shared - specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure.