How do I break out of this while loop which is inside a coroutine? The debug message appears continuously even after the value is reached.   void Start()     {         StartCoroutine(StartFadingIn());      } IEnumerator StartFadingIn()     {         float i = 0f;         while(i!=1f)         {             Color color = Downward.material.color;             color.a = i;             Downward.material.color = color;             yield return new WaitForSeconds(0.05f);             i = i+0.1f;             Debug.Log("Repeat");         }     }
27
Consider the following code:   0.1 + 0.2 == 0.3  -&gt;  false   0.1 + 0.2         -&gt;  0.30000000000000004   Why do these inaccuracies happen?
8886
I've seen this done in Borland's  environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?
96539
I keep wondering how does a debugger work? Particulary the one that can be 'attached' to already running executable. I understand that compiler translates code to machine language, but then how does debugger 'know' what it is being attached to?
118792
The following code  using System.Threading;  class Test {     volatile int counter = 0;     public void Increment()     {         Interlocked.Increment(ref counter);     } }   Raises the following compiler warning:  "A reference to a volatile field will not be treated as volatile"   Am I doing something wrong here to raise this warning? Why does the compiler me warn about this?
41653
I want an object to rotate after a delay. I tried using StartCoroutine, yield and WaitForSeconds, but failed. How can I do it?
112570
Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It's kind of cumbersome and I'm wondering if there is a more straightforward approach.
1371
I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference?  A (quite pointless) example in Java:  a) declaration before loop:  double intermediateResult; for(int i=0; i &lt; 1000; i++){     intermediateResult = i;     System.out.println(intermediateResult); }   b) declaration (repeatedly) inside loop:  for(int i=0; i &lt; 1000; i++){     double intermediateResult = i;     System.out.println(intermediateResult); }   Which one is better, a or b?   I suspect that repeated variable declaration (example b) creates more overhead in theory, but that compilers are smart enough so that it doesn't matter. Example b has the advantage of being more compact and limiting the scope of the variable to where it is used. Still, I tend to code according example a.  Edit: I am especially interested in the Java case.
11091
When debugging an application in Visual Studio, there are 2 options for breaking on exceptions. Break as soon as an exception is thrown, and breaking only when an exception isn't caught. This works fine when developing desktop applications. However, when developing ASP.NET applications, all exceptions are eventually caught by the code in IIS.  Is it possible to disable this behavior, so that the debugger breaks when my ASP.Net application code fails to catch an exception?  Edit: Just to be clear, I don't want to break whenever an exception is thrown, as many times they are handled just fine by my code, and I don't want to stop on every exception. I only want to stop on the exceptions that aren't handled by my code.  Edit: This seems to not be an issue in Visual Studio 2008. In Visual Studio 2003, all exceptions were treated as user handled, because the ASP.NET runtime caught all the exceptions so as not to bring down the web server process. It seems that in Visual Studio 2008, this type of exception catching is not counted when checking for user-unhandled exceptions.
80132
I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.
69477
I have a scenario where I have multiple threads adding to a queue and multiple threads reading from the same queue. If the queue reaches a specific size all threads that are filling the queue will be blocked on add until an item is removed from the queue.  The solution below is what I am using right now and my question is: How can this be improved?  Is there an object that already enables this behavior in the BCL that I should be using?  internal class BlockingCollection&lt;T&gt; : CollectionBase, IEnumerable {     //todo: might be worth changing this into a proper QUEUE      private AutoResetEvent _FullEvent = new AutoResetEvent(false);      internal T this[int i]     {         get { return (T) List[i]; }     }      private int _MaxSize;     internal int MaxSize     {         get { return _MaxSize; }         set         {             _MaxSize = value;             checkSize();         }     }      internal BlockingCollection(int maxSize)     {         MaxSize = maxSize;     }      internal void Add(T item)     {         Trace.WriteLine(string.Format("BlockingCollection add waiting: {0}", Thread.CurrentThread.ManagedThreadId));          _FullEvent.WaitOne();          List.Add(item);          Trace.WriteLine(string.Format("BlockingCollection item added: {0}", Thread.CurrentThread.ManagedThreadId));          checkSize();     }      internal void Remove(T item)     {         lock (List)         {             List.Remove(item);         }          Trace.WriteLine(string.Format("BlockingCollection item removed: {0}", Thread.CurrentThread.ManagedThreadId));     }      protected override void OnRemoveComplete(int index, object value)     {         checkSize();         base.OnRemoveComplete(index, value);     }      internal new IEnumerator GetEnumerator()     {         return List.GetEnumerator();     }      private void checkSize()     {         if (Count &lt; MaxSize)         {             Trace.WriteLine(string.Format("BlockingCollection FullEvent set: {0}", Thread.CurrentThread.ManagedThreadId));             _FullEvent.Set();         }         else         {             Trace.WriteLine(string.Format("BlockingCollection FullEvent reset: {0}", Thread.CurrentThread.ManagedThreadId));             _FullEvent.Reset();         }     } }
11909
I'm developing an Windows Forms application that requires me to call a separate program to perform a task.  The program is a console application and I need to redirect standard output from the console to a TextBox in my program.    I have no problem executing the program from my application, but I don't know how to redirect the output to my application.  I need to capture output while the program is running using events.    The console program isn't meant to stop running until my application stops and the text changes constantly at random intervals.  What I'm attempting to do is simply hook output from the console to trigger an event handler which can then be used to update the TextBox.  I am using C# to code the program and using the .NET framework for development.  The original application is not a .NET program.  EDIT: Here's example code of what I'm trying to do.  In my final app, I'll replace Console.WriteLine with code to update the TextBox.  I tried to set a breakpoint in my event handler, and it isn't even reached.      void Method()     {         var p = new Process();         var path = @"C:\ConsoleApp.exe";          p.StartInfo.FileName = path;         p.StartInfo.UseShellExecute = false;         p.OutputDataReceived += p_OutputDataReceived;          p.Start();     }      static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)     {         Console.WriteLine("&gt;&gt;&gt; {0}", e.Data);     }
23361
I have the following code in Visual Studio 2005.      Dim OutFile As System.IO.StreamWriter     Try         OutFile = New System.IO.StreamWriter(Filename)        // Do stuff with OutFile     Catch Ex As Exception        // Handle Exception     Finally        If OutFile IsNot Nothing Then OutFile.Close()     End Try   But VS2005 brings up the warning for the line "If OutFile IsNot.." that      Variable 'OutFile' is used before it has been assigned a value. A null reference exception could result at runtime.   Is there some way of removing this warning by subtly altering the code or is there just a better way of doing what I'm trying to do?  Thanks  Rob
56379
I'm writing a wrapper class for a command line executable.  This exe accepts input from stdin until I hit Ctrl+C in the command prompt shell, in which case it prints output to stdout based on the input.  I want to simulate that Ctrl+C press in C# code, sending the kill command to a .NET Process object.  I've tried calling Process.Kill(), but that doesn't seem to give me anything in the process's StandardOutput StreamReader.  Might there be anything I'm not doing right?  Here's the code I'm trying to use:  ProcessStartInfo info = new ProcessStartInfo(exe, args); info.RedirectStandardError = true; info.RedirectStandardInput = true; info.RedirectStandardOutput = true; info.UseShellExecute = false; Process p = Process.Start(info);  p.StandardInput.AutoFlush = true; p.StandardInput.WriteLine(scriptcode);  p.Kill();  string error = p.StandardError.ReadToEnd(); if (!String.IsNullOrEmpty(error))  {     throw new Exception(error); } string output = p.StandardOutput.ReadToEnd();   The output is always empty, even though I get data back from stdout when I run the exe manually.  Edit: This is C# 2.0 by the way.
105996
When I'm debugging, I often have to deal with methods that does not use an intermediate variable to store the return value :     private int myMethod_1()    {       return 12;    }     private int myMethod_2()    {       return someCall( someValue );    }   Well, in order to recreate a bug, I often have to change values on the fly. Here, I could want to see what happens when myMethode_1 return zero. Same thing for myMethod_2.  Is there a way to do that without modifying the code ? What I would like to do, it's to place a breakpoint on the return line (or on the closing bracket) and type-in a new return value.  Note : I'm using Visual Studio 2005 and Visual Studio 2008.  Thank !
68609
I closed an application, but the process remained in the list. I try to stop in from the task manager, but nothing happens. No error messages, process just stays in the list. I try to debug it, but the debugger says:     Unable to attach to the crashing process. The requested operation is not supported.     This happens with VS2008 and some other programs, sometimes.  How to terminate it?
58103
I was answering a question and this little inconsistency popped up.  Just wondering if anyone has come across it before, or if anyone knows why this happens.  A variable that is declared within some form of scoped element (if, for loop, etc.) shouldn't be available outside that scope.  i.e.  {     // accountNames variable is not available outside this scope     Set&lt;String&gt; accountNames = new Set&lt;String&gt; {'Test Account'}; }  system.debug(accountNames);   This debug statement fails with the message:      Variable does not exist: accountNames   However, if this is part of a query string being generated, the Database.query() call somehow has access to it.  String queryString = 'SELECT Id, Name FROM Account';  if(true) {     // accountNames variable is not available outside the `if` statement     Set&lt;String&gt; accountNames = new Set&lt;String&gt; {'Test Account'};     queryString += ' WHERE Name IN :accountNames'; }  // this debug will fail if you uncomment it // system.debug(accountNames);  // however the query somehow has access to it. // create an account called Test Account to prove it.  system.debug('queryString: ' + queryString); system.debug('queryString result: ' + database.query(queryString));   But, Salesforce is smart enough to know that it's not just some random string, so the following will fail:  // Alternatively, use a random string as the variable name, and salesforce  // is smart enough to know it's gibberish String queryString2 = 'SELECT Id, Name FROM Account';  if(true) {     queryString2 += ' WHERE Name IN :randomString'; }  try {     system.debug('queryString2 result: ' + database.query(queryString2));     system.assert(false); } catch (QueryException qe)  {     system.debug(':randomString is gibberish: ' + qe.getMessage()); }     Edit:  Interestingly, the :randomString is definitely calculated only when the query is executed.  String queryString3 = 'SELECT Id, Name FROM Account'; String queryString4 = 'SELECT Id, Name FROM Account';  if(true) {     // assign to query 3 before it has a value     queryString3 += ' WHERE Name IN :randomString';      // assign to query 4 after it has been declared     Set&lt;String&gt; randomString = new Set&lt;String&gt;{'Test Account'};     queryString4 += ' WHERE Name IN :randomString'; }  // both queries return correct results, regardless of when the variable was declared system.debug('queryString3 result: ' + database.query(queryString3)); system.debug('queryString4 result: ' + database.query(queryString4));   But it's not an open slather.  The following throws an error:  String queryString = 'SELECT Id, Name FROM Account WHERE Name = :someField'; someMethod(); system.debug('queryString result: ' + database.query(queryString));  void someMethod() {     String someField = 'Test Account';     system.debug('someField: ' + someField); }     Does anyone know why this is the case, or have an explanation why this would work?  As far as I can tell, at the time that the accountNames variable is in scope, no part of the code knows that it's anything other than a string.
56415
I have four foreach loops that iterate through the collections and based on a condition do something.   Here is the code that I am writing now:  boolean breakFlag = false; String valueFromObj2 = null; String valueFromObj4 = null; for(Object1 object1: objects){   for(Object2 object2: object1){     // I get some value from object2     valueFromObj2 = object2.getSomeValue();     for(Object3 object3 : object2){       for(Object4 object4: object3){        // Finally I get some value from Object4.        valueFromObj4 = object4.getSomeValue();        // Compare with valueFromObj2 to decide either to break all the foreach loop        breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );        if(breakFlag){break;}       } // fourth loop ends here       if(breakFlag){break;}     } // third loop ends here     if(breakFlag){break;}   } // second loop ends here   if(breakFlag){break;} } // first loop ends here   The main object (objects in the code) comes from a third-party provider SDK, so I cannot change anything on that portion. I want to ask the Stack&nbsp;Overflow community if there is a better approach to break all the four foreach loops. Or if there is any other way to refactor this code to make it more readable and maintainable.