C# Question about globals

csharp United States
  • 12 years ago

    I've been working with VB.NET/VB6 in the past and recently we've been pushed to move over to C#. I was wondering, how does one make a global variable in C#?

    in VB.NET we have modules that (like in VB6) i can declare a class and I can use that class throughout the entire application. But I see no alternative in C#.

    The reason for this is because we have a class called a "KernelWrap" that has all the functions we need for our application to run, inside that class we instantiate other objects and destory those objects when the KernelWraps class's destructor runs so we cant make the methods static and get away with it.

  • 12 years ago

    In order to do that, you need to need to use the static keyword. For example

    namespace NyNamespace {
    public class MyClass {
       public static SomeSharedVariable = "hello";
       public static void SomeSharedMethod() { // do something }

    You can then access MyNamespace.MyClass.SomeSharedVariable and call MyNamespace.MyClass.SomeSharedMethod without instantiating the MyClass class.

  • 12 years ago

    i thought static clases dont have deconstructors etc. in the constructor we create (and hold) an object to ADO.NET db connection and its maintained till the class is destroyed... this cant be kept in a static class can it?

  • 12 years ago
    You're correct. If you've got an instantiated class, then either all your other code will need references to it - or you create a static variable that points to the instance of that KernelWrap class - that is initialized when the application is first started

    static KernelWrap kernelInstance;

    // starting application...
    kernelInstance = new KernelWrap();

    // then everyone can access the static variable...

    does that make sense?

Post a reply

Enter your message below

Sign in or Join us (it's free).


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why.”