C# global module

10,674

Solution 1

There is nothing as Global Module in C# instead you can create a Public class with Static Members like:

Example:

//In a class file 

namespace Global.Functions //Or whatever you call it
{
  public class Numbers
  {
    private Numbers() {} // Private ctor for class with all static methods.

    public static int MyFunction()
    {
      return 22;
    }
  }
}

//Use it in Other class 
using Global.Functions
int Age = Numbers.MyFunction();

Solution 2

No, this requires help from a compiler. A VB.NET module gets translated to a class under the hood. Which is very similar to a static class in C#, another construct that doesn't have a real representation in the CLR. Only a compiler could then pretend that the members of such a class belong in the global namespace. This is otherwise a compat feature of the VB.NET compiler, modules were a big deal in the early versions of visual basic.

A static class declared without a namespace is the closest you'll get in C#. Util.Foo(), something like that.

Share:
10,674
jackie
Author by

jackie

Updated on June 04, 2022

Comments

  • jackie
    jackie almost 2 years

    I'm new to c# and I was wondering if someone could tell me how to create a global module for changing a form like you would do in vb, and then how to call that module.

    Thanks

    Update:

    Ok so i have multiple forms and instead of writing the same 2 lines over and over, which are..

    Form x = new Form1();
    x.Show();
    

    Is it possible to add this to a class to make it easier. How do i do it? never made a class before. got the class up but unsure how to write the code.