C# Question about globals

csharp United States
  • 12 years ago
    Hi,

    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.

    thanks
  • 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).

Contribute

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.

“PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil perpetrated by skilled but perverted professionals.” - Jon Ribbens