Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global "Module" in C# similar to VB.NET's Module

Tags:

c#

.net

vb.net

I've been searching around here and elsewhere for an answer to this, but I haven't found an exact answer.

I'm fairly new to C#. In VB.NET, you can define a Module, like a class, which has some limitations and also some benefits. One of its great benefits is that you can access all of its members globally if you've imported the namespace (i.e. "using" in c#). For example:

Private Sub Test()
    MsgBox(Now)
End Sub

In the method above, MsgBox is a method in the Microsoft.VisualBasic.Interaction module and Now is a property in the Microsoft.VisualBasic.DateAndTime module. I don't have to qualify the call to either of them in order to use them, although I could:

Private Sub Test()
    Microsoft.VisualBasic.Interaction.MsgBox(Microsoft.VisualBasic.DateAndTime.Now)
End Sub

I use this feature all the time in my own projects by building my own modules with utility methods and properties. It's very, very useful. Is there an equivalent in C#?

like image 274
rory.ap Avatar asked Dec 06 '25 20:12

rory.ap


1 Answers

A module in VB.NET is the exact equivalent of a static class in C#. The only difference is that the VB.NET compiler by default puts your declarations inside the Module in the global namespace. This is a practice that the C# team does not favor, for a good reason, you have to use the class name when you reference a member of the static class in the rest of your code. In other words, you have to use Math.Pi, not just Pi.

It doesn't have to be this way, you can put a Module in a Namespace:

Namespace Contoso.Foobar
    Module MyModule
        '' etc..
    End Module
End Namespace

Now it is the same thing.

like image 57
Hans Passant Avatar answered Dec 08 '25 12:12

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!