C# Equivalent for VB 'module'

16.4k views Asked by At

In Visual Basic, you can use a module as a place to store 'loose' code which can be methods and variables that are accessible from elsewhere in the application without having to first initialize something, and the variable states can be set or changed and will continue to keep that value throughout.

The closest I have found, is static methods in C# as part of a public class, however this has the drawback of variables which are not globally accessible, or internally settable/gettable if the variables are made static.

Take for example the following simple code in VB stored in a blank module.

Private iCount as Integer = 0

Public Sub Increment()
  iCount = iCount + 1
End Sub

Public CheckModulus() As Boolean
  If iCount % 6 == 0 Then
    Return True
  Else
    Return False
  End If
End Sub

Now, you have a class, and from that class, you can then call CheckModulus() as such

Public Class Fruits

   Public Static Function ExactBunches() As String
      If CheckModulus() Then
         Return "You have an exact amount of bunches"
      Else
         Return "You need more fruits to make a bunch"
      End If
   End Function

End Class

Now I realize with some hack and slash, that you could move iCount to 'settings', and reset it on application launch, etc, but please bear in mind this is a very simple example to illustrate the convenience of being able to have a set of global code. Where I have found this most useful in the past is when creating UserControls or custom classes. In addition, the intent is not to make everything globally accessable, but to have certain methods and variables globally accessable while others remain ONLY accessible from within the module. For example, while CheckModulus() and Increment() (global methods) both have access to modify and obtain the iCount value, iCount is not accessible globally, as would the way be with private defined methods in the module.

So the big pickle is this :

What is the functionally equivalent code type in C# to VB & VB.NET's module ?

Due to the complex nature of this simple question, I feel I should impose a boolean for a 'just in case there is no answer' answer as follows.

If, there is nothing functionally equivalent, then what sort of clever hack or workaround (aside from using settings, or external storage like the registry, database, files, etc), to make this happen or something VERY very close ?

2

There are 2 answers

3
DavidG On BEST ANSWER

You can use a static class. You can also initialise these using a static constructor.

public static class MyStuff
{
    //A property
    public static string SomeVariable { get; set; }

    public static List<string> SomeListOfStuff { get; set; }
    //Init your variables in here:
    static MyStuff()
    {
        SomeVariable = "blah";
        SomeListOfStuff = new List<string>();
    }

    public static async Task<string> DoAThing()
    {
        //Do your async stuff in here
    }

}

And access it like this:

MyStuff.SomeVariable = "hello";
MyStuff.SomeListOfStuff.Add("another item for the list");
11
Matt Burland On

A static class like this would be equivalent to your VB code:

public static class MyModule
{
    private static int iCount = 0;   // this is private, so not accessible outside this class

    public static void Increment()
    {
        iCount++;
    }

    public static bool CheckModulus()
    {
        return iCount % 6 == 0;
    }

    // this part in response to the question about async methods
    // not part of the original module
    public async static Task<int> GetIntAsync()
    {
        using (var ms = new MemoryStream(Encoding.ASCII.GetBytes("foo"))) 
        {
            var buffer = new byte[10];
            var count = await ms.ReadAsync(buffer, 0, 3);
            return count;
        }
    }
}

You would then call it like this (and the value of iCount does persist because it's static):

    // iCount starts at 0
    Console.WriteLine(MyModule.CheckModulus());   // true because 0 % 6 == 0
    MyModule.Increment();                         // iCount == 1
    Console.WriteLine(MyModule.CheckModulus());   // false
    MyModule.Increment();                         // 2
    MyModule.Increment();                         // 3
    MyModule.Increment();                         // 4
    MyModule.Increment();                         // 5
    MyModule.Increment();                         // 6
    Console.WriteLine(MyModule.CheckModulus());   // true because 6 % 6 == 0
    Console.WriteLine(MyModule.GetIntAsync().Result);   // 3

A fiddle - updated with an async static method