CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Nov 2008
    Location
    .NET 4.0/VS 2010
    Posts
    11

    Variables between methods.

    Hello again. This time I am having problems passing variables between methods.

    Example

    public static void Method1()
    {
    int var1 = 1;
    }

    public static void Method2()
    {
    int var2 = var1;
    }

    ...

    do you see what I am getting at?

  2. #2
    Join Date
    Nov 2009
    Posts
    4

    Re: Variables between methods.

    I think you should declare the var in the class outside the void.

  3. #3
    Join Date
    Jul 2008
    Location
    Germany
    Posts
    210

    Re: Variables between methods.

    use parameters in your methods to pass values

    Code:
    public static void Method1()
    {
        int var1 = 1;
        Method2(var1);
    }
    
    public static void Method2(int inputParam)
    {
        int var2 = inputParam; // var2 is now 1
    }
    Last edited by MNovy; November 9th, 2009 at 03:30 AM.

  4. #4
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Variables between methods.

    Make it an instance variable
    Code:
    class Foo
    {
       int var1 = 1;
    
       public static void Method1()
      {
         var1 = 1;
       }
    
       public static void Method2()
       {
          int var2 = var1;
        }
    }
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  5. #5
    Join Date
    Oct 2009
    Posts
    8

    Re: Variables between methods.

    I find this just depends how decisive you are, how you change your class to use a global variable.
    You might be warned of the value that may have been changed while passing

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