Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a common function for all forms using c#?

Tags:

c#

.net

vb.net

I need to call a single function from all forms. In vb.net there is an option module. In this module we can create functions/variables and we call them from anywhere in the project. Is there any option in C# like this module? Finally, if I need to use a single function in my entire project, is this possible or not?

like image 482
Sivashankar Avatar asked Dec 04 '25 11:12

Sivashankar


1 Answers

Are you looking for a static class?

 namespace MyNamespace {
   ...
   public static class MyStaticClass {
     public static int MyFunc(int x) {
       return x * 2;
     } 
   }
   ...
 }

And you can call it

 using MyNamespace;

 ...

 int result = MyStaticClass.MyFunc(123);

you may want to add static import in order to get rid of MyStaticClass:

 using static MyNamespace.MyStaticClass;

 ...

 // Just "MyFunc", no need to the class name being mentioned 
 int result = MyFunc(123);
like image 122
Dmitry Bychenko Avatar answered Dec 06 '25 23:12

Dmitry Bychenko