CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15
  1. #1
    Join Date
    Jun 2010
    Location
    Kathmandu
    Posts
    27

    How to define global variables

    I want to define global variables specially for application level variables. HOw and where to define for this purpose

  2. #2
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,284

  3. #3
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: How to define global variables

    Very bad idea. Global variables (i.e. statics in C#) tend to lead to hard to maintain code in my experience.

    I've found that 99% of the time global variables are used they're being used as a shortcut and not because they make sense design wise.

    I'd recommend not using singletons etc unless there's a very good reason to do so.

    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  4. #4
    Join Date
    Apr 2011
    Posts
    27

    Re: How to define global variables

    I use global variables often because I will have say one function that sets the variable and it might call a function that needs the variable and I can pass the variable to that function so all is well... until I end up with another function that runs when the user clicks on something that requires the same variable and has nothing to pass it along the chain.

  5. #5
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: How to define global variables

    I use global variables often because I will have say one function that sets the variable and it might call a function that needs the variable and I can pass the variable to that function so all is well... until I end up with another function that runs when the user clicks on something that requires the same variable and has nothing to pass it along the chain.
    In a large system with many developers this could cause you to become horribly unstuck - how does someone other than yourself know which global variables are being set by which functions ?

    This is where grouping functions in classes with member variables helps, not just making every variable in the system available to every piece of code in the system.

    I also think it would make the code very difficult to read and logically step though. If you pass back the results of every function you can watch the variables at every stage when debugging whereas I'd be pretty lost if every function set globals.

    I believe I already covered this case when I said

    used they're being used as a shortcut and not because they make sense design wise.
    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  6. #6
    Join Date
    Apr 2011
    Posts
    27

    Re: How to define global variables

    Oh I guess I have been using "Member variables" because they are only global within my class. I only have 1 Class though so in a way its "Global"

  7. #7
    Join Date
    Jun 2008
    Posts
    2,477

    Re: How to define global variables

    Quote Originally Posted by DeepThought View Post
    Oh I guess I have been using "Member variables" because they are only global within my class. I only have 1 Class though so in a way its "Global"
    Global variables mean application scope variables, not class scope. Strictly there is no such thing as a "global variable" in C#. You can however use public static fields/properties in a class to get the same effect, but as darwen points out it is often a bad idea from a design perspective.

  8. #8
    Join Date
    Apr 2011
    Posts
    27

    Unhappy Re: How to define global variables

    Speaking of Global Variables and access. How do I get my background worker to access a varaible. It doesn't even seem to be able to see member variables. Simple example:

    Code:
    string temp = "";
    
    BackgroundWorker worker = new BackgroundWorker();
    
    worker.DoWork += delegate(object s, DoWorkEventArgs args)
    {
    
    temp = "Hello World";
    
    };
    
     worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
    {
    textblock1.Text = temp;
    };
    
    worker.RunWorkerAsync();
    Never sets textblock1.Text to = "Hello World"

  9. #9
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: How to define global variables

    "temp" isn't a member variable - it's a variable in local scope. So you'll end up with copies of the temp variable in each of the delegate anonymous methods.

    Be careful when using anonymous methods referencing variables declared outside them - see closures.

    You should do something like :

    Code:
    class Example
    {
        private string _temp;
    
        public void Run(TextBox textBox)
        {
              BackgroundWorker worker = new BackgroundWorker();
    
              // I prefer lambda function declarations to the older, C# 2.0 anonymous method declarations
              worker.DoWork += 
                  (s, args) =>
                  {
                        _temp = "Hello World";          
                  };
    
              worker.RunWorkerCompleted += 
                  (s, args) =>          
                  {
                        textBox.Text = _temp;
                  };
    
              worker.RunWorkerAsync();
        }
    }
    
    // to use
    Example x = new Example();
    x.Run(textBox);
    This would be clearer of course if you use separate methods which are defined in the class as the delegates rather than inline anonymous methods.

    Darwen.
    Last edited by darwen; April 28th, 2011 at 06:46 PM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  10. #10
    Join Date
    Jan 2010
    Posts
    1,133

    Re: How to define global variables

    Quote Originally Posted by darwen View Post
    Be careful when using anonymous methods referencing variables declared outside them - see closures.
    What a beautiful article - I love it.

    I do have a question, though: when is closure-like behavior really beneficial?
    The only thing I can think of is the case where a first-class function operates on an expensive-to-create object (free variable)... that could be passed as a parameter, on the other hand.

  11. #11
    Join Date
    Apr 2011
    Posts
    18

    Re: How to define global variables

    As far as I remember, Global variabls are those variables that are defined before declaration of the main() function.

    #include<iostream.h>
    int i; //Global variable
    void main()
    {
    .......
    .......
    ....
    ....
    }
    Source(s):
    My memory

  12. #12
    Join Date
    Jun 2010
    Location
    Kathmandu
    Posts
    27

    Re: How to define global variables

    but i need it in whole application level where i can use it within whole appplicaiton not only one class.

  13. #13
    Join Date
    Apr 2011
    Posts
    27

    Re: How to define global variables

    Hi Darwen,

    The primary difference I see here is that you are passing the textbox into the function. I re-wrote my code exactly like yours into my class, however I get the following error when trying to pass my UI elements into the function.

    The calling thread cannot access this object because a different thread owns it.

    Quote Originally Posted by darwen View Post
    "temp" isn't a member variable - it's a variable in local scope. So you'll end up with copies of the temp variable in each of the delegate anonymous methods.

    Be careful when using anonymous methods referencing variables declared outside them - see closures.

    You should do something like :

    Code:
    class Example
    {
        private string _temp;
    
        public void Run(TextBox textBox)
        {
              BackgroundWorker worker = new BackgroundWorker();
    
              // I prefer lambda function declarations to the older, C# 2.0 anonymous method declarations
              worker.DoWork += 
                  (s, args) =>
                  {
                        _temp = "Hello World";          
                  };
    
              worker.RunWorkerCompleted += 
                  (s, args) =>          
                  {
                        textBox.Text = _temp;
                  };
    
              worker.RunWorkerAsync();
        }
    }
    
    // to use
    Example x = new Example();
    x.Run(textBox);
    This would be clearer of course if you use separate methods which are defined in the class as the delegates rather than inline anonymous methods.

    Darwen.

  14. #14
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: How to define global variables

    Google for that error and you'll find about 100,000 articles on why you get it and how to fix it.

    Actually the BackgroundWorker class should take care of this for you - are you calling Run() from a separate thread than your UI thread ? If so, don't.

    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  15. #15
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How to define global variables

    Quote Originally Posted by rajendradhakal View Post
    but i need it in whole application level where i can use it within whole appplicaiton not only one class.
    While you can't have 'real' global variables in C#, you can simulate them.

    Just create a static class with a static property.
    Code:
    internal static class MyClass
    {
      public static int Prop { get; set; }
    
    }
    Next, access the static variable from anywhere in your code.
    Code:
    // some class's member method
    void Foo( )
    {
      // retrieve the 'global' value
      int value = MyClass.Prop;
    
      // set the 'global' value
      MyClass.Prop = 15;
    
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured