locked
Define Global Objects In Middle Of Functions RRS feed

  • Question

  • I Am Trying To Define Global Objects (string For Example) In Middle Of A Function (Their Properties Are Set In The Specified Function) That I Want Them To Be Accessible From Other Functions And Events. Normally You Can Define Them Outside The Function And Access Them Wherever You Want But How Is This Possible???
    Monday, June 18, 2012 5:28 PM

Answers

  • You can't define a "global" (or static) variable within a method in C#.  It needs to be defined within the enclosing type (typically the class).

    Note that VB.Net does provide a way to make method-level static variables, but they are mapped into class level variables by the compiler, so the end result is the same as if you define them in the class.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by BVaraminian Monday, June 18, 2012 5:38 PM
    Monday, June 18, 2012 5:32 PM
    Moderator

All replies

  • You can't define a "global" (or static) variable within a method in C#.  It needs to be defined within the enclosing type (typically the class).

    Note that VB.Net does provide a way to make method-level static variables, but they are mapped into class level variables by the compiler, so the end result is the same as if you define them in the class.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by BVaraminian Monday, June 18, 2012 5:38 PM
    Monday, June 18, 2012 5:32 PM
    Moderator
  • So What's The Solution If I Want To Access A StreamWriter Outside OF Where It Is Defined????

    You would need to define it at the class level, instead:

    class YourClass
    {
        private StreamReader sr;
    
    
        public void Open()
        {
           // this method can use it...
           sr = new StreamReader("filename.txt");
        }
    
        public string GetLine()
        {
            // This method can use the same variable, because it's defined at a class level...
            return sr.ReadLine();
        }
    }

    If that's not your goal, can you provide some pseudo-code showing what exactly you're trying to accomplish?


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Monday, June 18, 2012 5:38 PM
    Moderator
  • So What's The Solution If I Want To Access A StreamWriter Outside OF Where It Is Defined????
    1. Change where it is defined such that you can access it where you need to
    2. Pass around references to the objects rather than just increasing their scope
    3. You don't.
    Monday, June 18, 2012 5:39 PM