Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare global function or method using c#?

Tags:

c#

Can anyone tell me how to declare a global function in c#, similar to what a Module does in VB.net? I need to call a function that can be called in my form1, form2, and form3.


i have this code :

using System.Data.OleDb;

namespace XYZ
{
    public static class Module
    {
        public static void dbConnection()
        {
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = "provider= microsoft.jet.oledb.4.0;data source=..\\dbCooperative.mdb";
            con.Open();
        }
    }
}

and form1:

using System.Data.OleDb;
using XYZ;

namespace XYZ
{
    public partial class frmReports : Form
    {
        public frm1()
        {
            InitializeComponent();
        }

        private void frm1_Load(object sender, EventArgs e)
        {
            Module.dbConnection();
            OleDbCommand cm = new OleDbCommand("SELECT * FROM table", con);
        }
    }
}

but i has an error: "The name 'con' does not exist in the current context".

like image 393
anonymizer Avatar asked Jun 23 '12 14:06

anonymizer


2 Answers

If you're using C# 6.0 or later, you could use using static.

For example,

using static ConsoleApplication.Developer;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // Global static function, static shorthand really 
            DeveloperIsBorn(firstName: "Foo", lastname: "Bar")
                .MakesAwesomeApp()
                .Retires();
        }
    }
}

namespace ConsoleApplication
{
    class Developer
    {
        public static Developer DeveloperIsBorn(string firstName, string lastname)
        {
            return new Developer();
        }

        public Developer MakesAwesomeApp()
        {
            return this;
        }

        public Developer InsertsRecordsIntoDatabaseForLiving()
        {
            return this;
        }

        public void Retires()
        {
           // Not really
        }        
    }
}

One more example:

using static System.Console;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("test");
        }
    }
}
like image 82
Alex Nolasco Avatar answered Nov 15 '22 18:11

Alex Nolasco


You could create a static class.

namespace MyNamespace
{
    public static class MyGlobalClass
    {
        public static void MyMethod() { ... }
    }
}

You would then add the namespace in the using section of your calling class to access it. Like this:

using MyNamespace;

public class CallingClass
{
    public  void CallingMethod()
    {
        MyGlobalClass.MyMethod();
    }
}
like image 22
Kevin Aenmey Avatar answered Nov 15 '22 17:11

Kevin Aenmey