7

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 ?

20
  • 3
    You can use a static class. Commented Jun 16, 2015 at 14:28
  • 2
    The problem I am having with static classes is accessibility levels. Commented Jun 16, 2015 at 14:30
  • 2
    possible duplicate of What would be considered a VB.NET module in C#? Commented Jun 16, 2015 at 14:30
  • 2
    I'm confused now. What do you mean by "pre-definable"? Also, why do you want your variables to be constant!? Commented Jun 16, 2015 at 14:33
  • 2
    @SanuelJackson You can initialise it, see my answer. Commented Jun 16, 2015 at 14:39

2 Answers 2

12

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Just a note, I respect this answer, and I feel with all the information here combined, I am getting closer to at least a workaround. For example, using the above in an internal scope would work, however there is still the problem of losing other functionality such as async methods since they must be static if in a static scope, but they can not be because C# doesn't support static async or even reverse it async static, as one case that poses a problem.
What makes you think static methods can't be async? I've added an example.
this is really strange XD .... when trying to do async in a static class today, it is actually working. It did remain black and with the standard class or method async doesn't exist, want to create it lol.... then it just went away after dropping the async verb on the form (test class is in the same file). Will have to see as I know this has given me compile issues in the past, but not gonna complain if it does work. Past failed compiles on attempts to do this are the reason I believed this.
7

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

11 Comments

How can the scope be narrowed to be accessible to only a particular set of calling classes and UserControls ? For example, I do not want this accessible from Form1, but I would like it accessible from within UserControl
Note that Static classes are not equivalent to Modules in VB. There are the closest thing to them however.
@SanuelJackson: You wanted it to be global, but now you want it restricted? You can restrict it some by careful positioning of your static class in relation to the classes intended to access it. For example, if it was internal in an assembly with your UserControls then it wouldn't be accessible outside.
A point nevertheless and I didn't say it was a good thing :-)
@SanuelJackson: Not sure where you get that idea from. See this updated fiddle. I've added an async static method and it compiles just fine. Although I would again suggest you really rethink your design if you need this many static classes and static methods.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.