Sivashankar Sivashankar - 5 days ago 5
C# Question

how to create common function for all forms using c#

i need to call a single function from all forms.In vb.net there is a option module.In this module we can create a functions/variable and we call this from entire project like this module there is any option in c#
finally my question is i need to use a single function in my entire project is this is possible or not

Answer

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);
Comments