Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. stack issue

stack issue

Scheduled Pinned Locked Moved C#
helpquestiondatabasedata-structures
22 Posts 4 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Goncalo Oliveira

    Consider the following code... string text; foreach ( something ) { if ( something ) { text = "closing"; someForm.FormClosing += delegate( object sender, FormClosingEventArgs e ) { MessageBox.Show( text ); }; } if ( something_else ) { text = "closed"; someForm.FormClosed += delegate( object sender, FormClosedEventArgs e ) { MessageBox.Show( text ); }; } } The foreach will have a something, and then a something_else, in this order. So, what will happen here, is that both events will trigger a MessageBox displaying "closed" text. To fix this, I passed the string text inside the foreach, and the issue isn't an issue anymore. Now... can anyone explain me why does this happen? The delegate uses the reference instead of the value?

    Gonçalo A.

    S Offline
    S Offline
    Skippums
    wrote on last edited by
    #6

    Why not just send the strings directly, without assigning to a variable?

    Sounds like somebody's got a case of the Mondays -Jeff

    G 1 Reply Last reply
    0
    • S Skippums

      Why not just send the strings directly, without assigning to a variable?

      Sounds like somebody's got a case of the Mondays -Jeff

      G Offline
      G Offline
      Goncalo Oliveira
      wrote on last edited by
      #7

      Skippums wrote:

      Why not just send the strings directly, without assigning to a variable?

      ahahahahahah :laugh: that's right, that would solve it. :) But that example is just an illustration of my problem. The actual code gets the contents from somewhere else dynamically, and it doesn't display a message box, it does something else... this was just to simplify. I actually solved this by moving the value holder inside the context, and this way, a new reference is always created.

      Gonçalo A.

      S 1 Reply Last reply
      0
      • G Goncalo Oliveira

        Skippums wrote:

        Why not just send the strings directly, without assigning to a variable?

        ahahahahahah :laugh: that's right, that would solve it. :) But that example is just an illustration of my problem. The actual code gets the contents from somewhere else dynamically, and it doesn't display a message box, it does something else... this was just to simplify. I actually solved this by moving the value holder inside the context, and this way, a new reference is always created.

        Gonçalo A.

        S Offline
        S Offline
        Skippums
        wrote on last edited by
        #8

        Kensho wrote:

        The actual code gets the contents from somewhere else dynamically...this was just to simplify

        Exactly... that is why Dave asked you for more specific code. Clearly, you would have thought of this if it solved your problem; however, in your example this is a valid solution. Try to be slightly more specific in your problem statement so we can give "real" feedback instead of having to guess what the problem is. Glad you got it working,

        Sounds like somebody's got a case of the Mondays -Jeff

        G 1 Reply Last reply
        0
        • S Skippums

          Kensho wrote:

          The actual code gets the contents from somewhere else dynamically...this was just to simplify

          Exactly... that is why Dave asked you for more specific code. Clearly, you would have thought of this if it solved your problem; however, in your example this is a valid solution. Try to be slightly more specific in your problem statement so we can give "real" feedback instead of having to guess what the problem is. Glad you got it working,

          Sounds like somebody's got a case of the Mondays -Jeff

          G Offline
          G Offline
          Goncalo Oliveira
          wrote on last edited by
          #9

          Ok... the thing is... I had solved it since I posted the first message here.. I said it even... I only spoke about the positioning of the variable and the association to runtime delegate. This is que only thing that I questioned:

          Kensho wrote:

          Now... can anyone explain me why does this happen? The delegate uses the reference instead of the value?

          delegate... value... I don't understand why the big fuss over a simple question. But nevermind... I already got my answer... maybe someone can pick this up and find it useful, as a simple piece of information, as it is. Cheers

          Gonçalo A.

          1 Reply Last reply
          0
          • G Goncalo Oliveira

            Cannot... or won't?? You tried it? Oh, there's just one detail on the code... replace the '1's with 'true'. Forgot that small detail in c#. Just Create a form, and on the constructor, after the initializations, add these lines: string text; if ( true ) { text = "closed"; FormClosed += delegate( object sender, FormClosedEventArgs e ) { MessageBox.Show( text ); }; } if ( true ) { text = "closing"; FormClosing += delegate( object sender, FormClosingEventArgs e ) { MessageBox.Show( text ); }; } And tell me if the output isn't "closing", "closing".

            Gonçalo A.

            D Offline
            D Offline
            Dave Kreskowiak
            wrote on last edited by
            #10

            Once again, the issue, as you described it, cannot occur with the code you posted. There is some tiny, yet important, little detail that's missing, (which you are ommiting because you think it's not important) that is probably causing this. If both if statements are using the same static value (NOT return values from two calls to the same function with the (supposedly) same data), then what you describe is not possible.

            A guide to posting questions on CodeProject[^]
            Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                 2006, 2007

            G 1 Reply Last reply
            0
            • D Dave Kreskowiak

              Once again, the issue, as you described it, cannot occur with the code you posted. There is some tiny, yet important, little detail that's missing, (which you are ommiting because you think it's not important) that is probably causing this. If both if statements are using the same static value (NOT return values from two calls to the same function with the (supposedly) same data), then what you describe is not possible.

              A guide to posting questions on CodeProject[^]
              Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                   2006, 2007

              G Offline
              G Offline
              Goncalo Oliveira
              wrote on last edited by
              #11

              Cannot, or it doesn't happen? Or... if it could not happen, then why, instead of just... cannot happen. Try it. Just as I described on my previous post. Create a new project, with a form, and type that out... Even I did this, to prove myself I wasn't fooling anyone; so I am not freaking ommiting anything... sheesh... This happens because when you add code like that, in runtime, the compiler will hold to the references and not to the values; the result is that both will grab the last value of the reference. That's why it won't happen if you switch the text variable to inside the if, or if you added static text like MessageBox( "closed" );. Advice... do try it first, before saying it CANNOT happen. I won't hold a grudge on you if you try, I promise... Cheers

              Gonçalo A.

              D 1 Reply Last reply
              0
              • G Goncalo Oliveira

                Cannot, or it doesn't happen? Or... if it could not happen, then why, instead of just... cannot happen. Try it. Just as I described on my previous post. Create a new project, with a form, and type that out... Even I did this, to prove myself I wasn't fooling anyone; so I am not freaking ommiting anything... sheesh... This happens because when you add code like that, in runtime, the compiler will hold to the references and not to the values; the result is that both will grab the last value of the reference. That's why it won't happen if you switch the text variable to inside the if, or if you added static text like MessageBox( "closed" );. Advice... do try it first, before saying it CANNOT happen. I won't hold a grudge on you if you try, I promise... Cheers

                Gonçalo A.

                D Offline
                D Offline
                Dave Kreskowiak
                wrote on last edited by
                #12

                I ignored your last code post because it's not the same as your original post.

                if (true)
                    ...
                
                if (true)
                    ...
                

                is NOT the same as:

                if (something)
                    ...
                
                if (something**\_else**)
                    ...
                

                Your last code post is identical in output to:

                string text;

                if (true)
                {
                text = "closed";
                FormClosed += delegate( object sender, FormClosedEventArgs e )
                { MessageBox.Show( text ); };

                text = "closing";
                FormClosing += delegate( object sender, FormClosingEventArgs e )
                    { MessageBox.Show( text ); };
                

                }

                The problem was never in the compiler, but in your logic.

                A guide to posting questions on CodeProject[^]
                Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                     2006, 2007

                G 1 Reply Last reply
                0
                • D Dave Kreskowiak

                  I ignored your last code post because it's not the same as your original post.

                  if (true)
                      ...
                  
                  if (true)
                      ...
                  

                  is NOT the same as:

                  if (something)
                      ...
                  
                  if (something**\_else**)
                      ...
                  

                  Your last code post is identical in output to:

                  string text;

                  if (true)
                  {
                  text = "closed";
                  FormClosed += delegate( object sender, FormClosedEventArgs e )
                  { MessageBox.Show( text ); };

                  text = "closing";
                  FormClosing += delegate( object sender, FormClosingEventArgs e )
                      { MessageBox.Show( text ); };
                  

                  }

                  The problem was never in the compiler, but in your logic.

                  A guide to posting questions on CodeProject[^]
                  Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                       2006, 2007

                  G Offline
                  G Offline
                  Goncalo Oliveira
                  wrote on last edited by
                  #13

                  You don't even need to put the if there... Now... all this not to answer my question?? Come one... you can do better than that, can't you? If I said that it wasn't relevant, it's because it wasn't... Now... you can remove the if... are you gonna answer my question or are you just gonna pretend you're so very awesome? Cheers

                  Gonçalo A.

                  D 2 Replies Last reply
                  0
                  • G Goncalo Oliveira

                    You don't even need to put the if there... Now... all this not to answer my question?? Come one... you can do better than that, can't you? If I said that it wasn't relevant, it's because it wasn't... Now... you can remove the if... are you gonna answer my question or are you just gonna pretend you're so very awesome? Cheers

                    Gonçalo A.

                    D Offline
                    D Offline
                    Dave Kreskowiak
                    wrote on last edited by
                    #14

                    Kensho wrote:

                    Come one... you can do better than that, can't you? If I said that it wasn't relevant, it's because it wasn't

                    That's what YOU think. It WAS relevant. The key piece of information was, and still is, missing. I already explained to why that's the case, but you keep insisting that it's not. It's not me that has the problem, it's you. The first rule of asking a question is to listen.

                    Kensho wrote:

                    Now... you can remove the if... are you gonna answer my question or are you just gonna pretend you're so very awesome?

                    I already answered this in my previous post. Sure, you can remove the if. Your code would still be this:

                    string text;
                    text = "closed";
                    FormClosed += delegate( object sender, FormClosedEventArgs e )
                    { MessageBox.Show( text ); };

                    text = "closing";
                    FormClosing += delegate( object sender, FormClosingEventArgs e )
                    { MessageBox.Show( text ); };

                    Perhaps you're misunderstanding what the two delegate statements are doing??

                    A guide to posting questions on CodeProject[^]
                    Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                         2006, 2007

                    1 Reply Last reply
                    0
                    • G Goncalo Oliveira

                      You don't even need to put the if there... Now... all this not to answer my question?? Come one... you can do better than that, can't you? If I said that it wasn't relevant, it's because it wasn't... Now... you can remove the if... are you gonna answer my question or are you just gonna pretend you're so very awesome? Cheers

                      Gonçalo A.

                      D Offline
                      D Offline
                      Dave Kreskowiak
                      wrote on last edited by
                      #15

                      Kensho wrote:

                      Come one... you can do better than that, can't you? If I said that it wasn't relevant, it's because it wasn't

                      That's what YOU think. It WAS relevant. The key piece of information was, and still is, missing. I already explained to why that's the case, but you keep insisting that it's not. It's not me that has the problem, it's you. The first rule of asking a question is to listen.

                      Kensho wrote:

                      Now... you can remove the if... are you gonna answer my question or are you just gonna pretend you're so very awesome?

                      I already answered this in my previous post. Sure, you can remove the if. Your code would still be this:

                      string text;
                      text = "closed";
                      FormClosed += delegate( object sender, FormClosedEventArgs e )
                      { MessageBox.Show( text ); };

                      text = "closing";
                      FormClosing += delegate( object sender, FormClosingEventArgs e )
                      { MessageBox.Show( text ); };

                      Perhaps you're misunderstanding what the two delegate statements are doing??

                      A guide to posting questions on CodeProject[^]
                      Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                           2006, 2007

                      G 1 Reply Last reply
                      0
                      • D Dave Kreskowiak

                        Kensho wrote:

                        Come one... you can do better than that, can't you? If I said that it wasn't relevant, it's because it wasn't

                        That's what YOU think. It WAS relevant. The key piece of information was, and still is, missing. I already explained to why that's the case, but you keep insisting that it's not. It's not me that has the problem, it's you. The first rule of asking a question is to listen.

                        Kensho wrote:

                        Now... you can remove the if... are you gonna answer my question or are you just gonna pretend you're so very awesome?

                        I already answered this in my previous post. Sure, you can remove the if. Your code would still be this:

                        string text;
                        text = "closed";
                        FormClosed += delegate( object sender, FormClosedEventArgs e )
                        { MessageBox.Show( text ); };

                        text = "closing";
                        FormClosing += delegate( object sender, FormClosingEventArgs e )
                        { MessageBox.Show( text ); };

                        Perhaps you're misunderstanding what the two delegate statements are doing??

                        A guide to posting questions on CodeProject[^]
                        Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                             2006, 2007

                        G Offline
                        G Offline
                        Goncalo Oliveira
                        wrote on last edited by
                        #16

                        If the code does the same, it WAS IRRELEVANT; if it was relevant, the code would do something different. I'll just state the output of that code... When you close the form, two message boxes will appear... One will say "closing", and the other one will say "closing". I said this right from the start.

                        Gonçalo A.

                        D 1 Reply Last reply
                        0
                        • G Goncalo Oliveira

                          Consider the following code... string text; foreach ( something ) { if ( something ) { text = "closing"; someForm.FormClosing += delegate( object sender, FormClosingEventArgs e ) { MessageBox.Show( text ); }; } if ( something_else ) { text = "closed"; someForm.FormClosed += delegate( object sender, FormClosedEventArgs e ) { MessageBox.Show( text ); }; } } The foreach will have a something, and then a something_else, in this order. So, what will happen here, is that both events will trigger a MessageBox displaying "closed" text. To fix this, I passed the string text inside the foreach, and the issue isn't an issue anymore. Now... can anyone explain me why does this happen? The delegate uses the reference instead of the value?

                          Gonçalo A.

                          S Offline
                          S Offline
                          S Senthil Kumar
                          wrote on last edited by
                          #17

                          One word : closures. A closure captures the value of a variable in its lexical scope. Your event handlers are anonymous functions which capture the local variable text. Behind the scenes, the compiler generates a new class with the captured variable as a member and rewires the event handler so that it calls a method on the generated class. That class then uses the member variable's value to fill in for the captured variable. The compiler updates the generated class instances with the value of captured variables as long as the captured variables are in scope. In your case, text was declared outside the scope of both if blocks, so the compiler dutifully updated the value of the variable when you changed it inside the second if block. Just to make things clear, this is not done only for reference types (like string).

                             delegate void Func();
                          
                              static void Main()
                              {
                                  Func\[\] f = new Func\[10\];
                                  for (int i = 0; i < 10; ++i)
                                  {
                                      f\[i\] = delegate { Console.WriteLine(i); };
                                  }
                          
                                  foreach (Func func in f)
                                  {
                                      func();
                                  }
                              }
                          

                          This will print 10 all ten times.

                          Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                          G 1 Reply Last reply
                          0
                          • S S Senthil Kumar

                            One word : closures. A closure captures the value of a variable in its lexical scope. Your event handlers are anonymous functions which capture the local variable text. Behind the scenes, the compiler generates a new class with the captured variable as a member and rewires the event handler so that it calls a method on the generated class. That class then uses the member variable's value to fill in for the captured variable. The compiler updates the generated class instances with the value of captured variables as long as the captured variables are in scope. In your case, text was declared outside the scope of both if blocks, so the compiler dutifully updated the value of the variable when you changed it inside the second if block. Just to make things clear, this is not done only for reference types (like string).

                               delegate void Func();
                            
                                static void Main()
                                {
                                    Func\[\] f = new Func\[10\];
                                    for (int i = 0; i < 10; ++i)
                                    {
                                        f\[i\] = delegate { Console.WriteLine(i); };
                                    }
                            
                                    foreach (Func func in f)
                                    {
                                        func();
                                    }
                                }
                            

                            This will print 10 all ten times.

                            Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                            G Offline
                            G Offline
                            Goncalo Oliveira
                            wrote on last edited by
                            #18

                            Exactly! Now that's an answer. Thank you. Cheers

                            Gonçalo A.

                            1 Reply Last reply
                            0
                            • G Goncalo Oliveira

                              If the code does the same, it WAS IRRELEVANT; if it was relevant, the code would do something different. I'll just state the output of that code... When you close the form, two message boxes will appear... One will say "closing", and the other one will say "closing". I said this right from the start.

                              Gonçalo A.

                              D Offline
                              D Offline
                              Dave Kreskowiak
                              wrote on last edited by
                              #19

                              if (true){
                              text = "closed";
                              FormClosed += delegate( object sender, FormClosedEventArgs e )
                              { MessageBox.Show( text ); };
                              text = "closing";
                              FormClosing += delegate( object sender, FormClosingEventArgs e )
                              { MessageBox.Show( text ); };
                              }

                              So you mean to tell me that you thought text in each delegate would get a copy of the current contents of the text variable when the delegates were created?? You'll have to excuse me as I (wrongly) assumed you knew how variables worked. This was such a basic concept you were missing that I didn't even consider it a possibility that that's where you were misunderstanding the code. To me, it was obvious this would be the behavior. I originally thought that you were wondering why both sections of code were being run because both if statements were being evaluated to true.

                              A guide to posting questions on CodeProject[^]
                              Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                   2006, 2007

                              G 1 Reply Last reply
                              0
                              • D Dave Kreskowiak

                                if (true){
                                text = "closed";
                                FormClosed += delegate( object sender, FormClosedEventArgs e )
                                { MessageBox.Show( text ); };
                                text = "closing";
                                FormClosing += delegate( object sender, FormClosingEventArgs e )
                                { MessageBox.Show( text ); };
                                }

                                So you mean to tell me that you thought text in each delegate would get a copy of the current contents of the text variable when the delegates were created?? You'll have to excuse me as I (wrongly) assumed you knew how variables worked. This was such a basic concept you were missing that I didn't even consider it a possibility that that's where you were misunderstanding the code. To me, it was obvious this would be the behavior. I originally thought that you were wondering why both sections of code were being run because both if statements were being evaluated to true.

                                A guide to posting questions on CodeProject[^]
                                Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                     2006, 2007

                                G Offline
                                G Offline
                                Goncalo Oliveira
                                wrote on last edited by
                                #20

                                bwahahahahaha I really had to laugh on this one... And you're a Microsoft MVP??? Well... you're from VB, so... I guess I have to understand. First... it's not a variable matter. It's a closures matter. And I said from the start what would happen; you were the one saying otherwise... so... don't try to cover up your stupidity now... And... weren't you supposed to be here to help? Get over your frustration, it's unhealthy for this forum users. Cheers

                                Gonçalo A.

                                D 1 Reply Last reply
                                0
                                • G Goncalo Oliveira

                                  bwahahahahaha I really had to laugh on this one... And you're a Microsoft MVP??? Well... you're from VB, so... I guess I have to understand. First... it's not a variable matter. It's a closures matter. And I said from the start what would happen; you were the one saying otherwise... so... don't try to cover up your stupidity now... And... weren't you supposed to be here to help? Get over your frustration, it's unhealthy for this forum users. Cheers

                                  Gonçalo A.

                                  D Offline
                                  D Offline
                                  Dave Kreskowiak
                                  wrote on last edited by
                                  #21

                                  One word: Blacklisted.

                                  A guide to posting questions on CodeProject[^]
                                  Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                       2006, 2007

                                  G 1 Reply Last reply
                                  0
                                  • D Dave Kreskowiak

                                    One word: Blacklisted.

                                    A guide to posting questions on CodeProject[^]
                                    Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                         2006, 2007

                                    G Offline
                                    G Offline
                                    Goncalo Oliveira
                                    wrote on last edited by
                                    #22

                                    In lack of a wiser answer... I don't mind... Cheers

                                    Gonçalo A.

                                    1 Reply Last reply
                                    0
                                    Reply
                                    • Reply as topic
                                    Log in to reply
                                    • Oldest to Newest
                                    • Newest to Oldest
                                    • Most Votes


                                    • Login

                                    • Don't have an account? Register

                                    • Login or register to search.
                                    • First post
                                      Last post
                                    0
                                    • Categories
                                    • Recent
                                    • Tags
                                    • Popular
                                    • World
                                    • Users
                                    • Groups