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".
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");
}
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With