advanced web statistics

Creating a Global Class File in C#

6/27/2006 1:17:19 PM

This task might seem trivial to most but I figured I would post for those that don`t know how to create "Global" classes in C#.  Global methods and variables are not supported in C# but you can place all of your common methods and variables within a class file and access them throughout your application.  Connection strings and log updaters are perfect candidates for this.  I ran into a couple of questions about this while cruising Google Groups.

Foo.cs

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

namespace Foo

{

   public abstract class Global

   {

      public static SqlConnection connection()

      {

         SqlConnection cn = new SqlConnection(...)

 

         return cn;

      }

 

      public static String stupid()

      {

         return "stupid";

      }

   }

}

Bar.cs

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

namespace Bar

{

   public class Default_Page

   {

      SqlConnection cn = Foo.Global.cn();

 

      private void Page_Load(object sender, System.EventArgs e)

      {

         Response.Write(Foo.Global.Stupid());

      } 

   }

}

C#, Code, Programming

kick it on DotNetKicks.com

Comments


Hi Will,

In classes with static members such as a global settings class, I usually go even further and mark the class as abstract. This way you can`t mistakenly attempt to instanciate the class either.

ie: you can`t do this:

Global g = new Global();
g.cn //...

but you can still do this:

Global.cn //...

Maybe I am just anal, but I just like to make it so that the class cannot be instanciated if it is not meant to have state.

-Ryan

Posted by: Ryan Farley | 8/6/2006 12:36:15 AM

Thanks for the feedback Ryan. I will have to become more anal from now on!

- Will

Posted by: Will | 8/6/2006 2:00:54 PM

hi,
this is umesh working in philips
can you tell me how can i access object which is in another funtion, for ex:
fn()
{
myArray obj=new myArray()
// some initiolisatio of obj data member
}
fn2()
{
//here i want to access obj data without passing the arguments
}
can you help me please....

Posted by: Umesh | 9/5/2006 2:31:45 AM

hi this is umesh
i want to create global object which is accessible by all classes..
ex:
class xyz
{
string[][] array;
int count;
}

and after this i want create one instance of that
xyz obj1=new xyz();

in some function i am initializing array and count and i want to acccess same values in some other class... how?
please help me



Posted by: Umesh | 9/5/2006 5:14:53 AM
Ace stuff! THanks a lot Will & Ryan! So then being anal help eh! ;-D

Posted by: smerch | 6/1/2007 3:11:44 AM

nice stuff i needed that so much , thnx

Posted by: mohscorpion | 10/31/2008 6:15:29 PM

Leave a Comment

   

  Enter the text to proceed!