I have a very simple C# .NET multitasking example that is not producing the result I expect.  (I am using VisualStudio 2017 on Windows 10, and this is a .NET Console application.)  Here is the code:  using System; using System.Threading.Tasks;  namespace Multithreading_Example {     class Program     {         static void Main(string[] args)         {             Task[] tasks = new Task[3];              for (int i = 0; i &lt; 3; i++)             {                 int n = i;                 tasks[i] = Task.Run(() =&gt; TestTask(i, n));             }             Console.ReadLine();         }          static void TestTask(int taskNum, int n)         {             Console.WriteLine("{0} {1}", taskNum, n);         }     } }   Here is the output that this program prints:  3 0 3 1 3 2   (The three lines of output could theoretically appear in a different order because the tasks are asynchronous, but that is fine.)  TestTask() simply prints the two integers that are passed to it.  Those two integers should be identical - one of them is the loop variable "i," and the second one is a new local variable "n" that is set to the same value as "i."  In other words, the above program should (it seems to me) produce this output:  0 0 1 1 2 2   The weird part, though, is when I run the program, TestTask() always prints "3" as the first number (see the actual output, above).  Why?  This feels like maybe some kind of optimization bug in the compiler, which is getting confused by the loop variable "i" being passed into the task.
1840
I met an interesting issue about C#. I have code like below.  List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();  int variable = 0; while (variable &lt; 5) {     actions.Add(() =&gt; variable * 2);     ++ variable; }  foreach (var act in actions) {     Console.WriteLine(act.Invoke()); }   I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.  It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.  Is there a way to work round this limit to have each action instance have its own captured variable?
34071
Consider this:  public class TestClass {      private String a;     private String b;      public TestClass()     {     a = "initialized";     }      public void doSomething()     {     String c;          a.notify(); // This is fine     b.notify(); // This is fine - but will end in an exception     c.notify(); // "Local variable c may not have been initialised"     }  }   I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?  Edit: making the members private was my initial intention, and the question still stands...
67728
Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)  #include &lt;iostream&gt;   int main() {    int a = 4;   int b = 5;   a, b = b, a;   std::cout &lt;&lt; "a: " &lt;&lt; a &lt;&lt; endl             &lt;&lt; "b: " &lt;&lt; b &lt;&lt; endl;    return 0; }   and prints:  a: 4 b: 5   What I'd like it to print ... if it weren't obvious, is:  a: 5 b: 4   As in, say, ruby, or python.
95803
I'm having problems trying to overload the post increment operator in C#. Using integers we get the following results.  int n;  n = 10; Console.WriteLine(n); // 10 Console.WriteLine(n++); // 10 Console.WriteLine(n); // 11  n = 10; Console.WriteLine(n); // 10 Console.WriteLine(++n); // 11 Console.WriteLine(n); // 11   But, when I try it using classes, it looks like the objects are exchanged.  class Account {     public int Balance { get; set; }     public string Name { get; set; }      public Account(string name, int balance)     {         Balance = balance;         Name = name;     }      public override string ToString()     {         return Name + " " + Balance.ToString();     }      public static Account operator ++(Account a)     {         Account b = new Account("operator ++", a.Balance);         a.Balance += 1;         return b;     }      public static void Main()     {         Account a = new Account("original", 10);          Console.WriteLine(a); // "original 10"          Account b = a++;          Console.WriteLine(b); // "original 11", expected "operator ++ 10"         Console.WriteLine(a); // "operator ++ 10", expected "original 11"     } }   Debugging the application, the overloaded operator method, returns the new object with the old value (10) and the object that has been passed by reference, has the new value (11), but finally the objects are exchanged. Why is this happening?
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
100125
The following method does not compile. Visual Studio warns "An out parameter may not be used within an anonymous method". The WithReaderLock(Proc action) method takes a delegate void Proc().  public Boolean TryGetValue(TKey key, out TValue value) {     Boolean got = false;     WithReaderLock(delegate     {         got = dictionary.TryGetValue(key, out value);     });     return got; }   What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).
38358
I've been learning C#, and I'm trying to understand lambdas.  In this sample below, it prints out 10 ten times.  class Program {     delegate void Action();     static void Main(string[] args)     {         List&lt;Action&gt; actions = new List&lt;Action&gt;();          for (int i = 0; i &lt; 10; ++i )             actions.Add(()=&gt;Console.WriteLine(i));          foreach (Action a in actions)             a();     } }   Obviously, the generated class behind the lambda is storing a reference or pointer to the int i variable, and is assigning a new value to the same reference every time the loop iterates.  Is there a way to force the lamda to grab a copy instead, like the C++0x syntax  [&amp;](){ ... } // Capture by reference   vs.  [=](){ ... } // Capture copies
74131
I was doing some software engineering and wanted to have a thread do something in the background to basically just waste CPU time for a certain test.  While I could have done something really boring like for(i &lt; 10000000) { j = 2 * i }, I ended up having the program start with $1$, and then for a million steps choose a random real number $r$ in the interval $[0,R]$ (uniformly distributed) and multiply the result by $r$ at each step.   When $R = 2$, it converged to $0$. When $R = 3$, it exploded to infinity.    So of course, the question anyone with a modicum of curiosity would ask: for what $R$ do we have the transition. And then, I tried the first number between $2$ and $3$ that we would all think of, Euler's number $e$, and sure enough, this conjecture was right. Would love to see a proof of this.    Now when I should be working, I'm instead wondering about the behavior of this script.   Ironically, rather than wasting my CPUs time, I'm wasting my own time. But it's a beautiful phenomenon. I don't regret it. $\ddot\smile$
25655
Do out parameters in C# have any performance implications I should know about? (Like exceptions)  I mean, is it a good idea to have a method with an out parameter in a loop that will run a couple of million times a second?  I know it's ugly but I am using it the same way as Int32.TryParse is using them - returning a bool to tell if some validation was successful and having an out parameter containing some additional data if it was successful.
646
For the longest time I have been using System.debug(JSON.Serialize(o)) to output objects to the debug log for troubleshooting purposes. This has worked up until my most recent project. Even existing code seems to be having this behavior.  I've tested API versions 41-45 with no luck. The actual line of code I'm using is:  system.debug(json.serialize(accountsToInsert)); // This is a map   I have also tried:  system.debug(json.serialize(accountsToInsert.get(Key)));   AND   Account test = accountsToInsert.get(Key); system.debug(json.serialize(test));   The code is called from a method defined in a VF page action attribute.  Is this just a thing that we have to live with now? Is there another way to get a  full look into the state of an object at run time?
52308
What tools are there available for static analysis against C# code? I know about FxCop and StyleCop. Are there others? I've run across NStatic before but it's been in development for what seems like forever - it's looking pretty slick from what little I've seen of it, so it would be nice if it would ever see the light of day.   Along these same lines (this is primarily my interest for static analysis), tools for testing code for multithreading issues (deadlocks, race conditions, etc.) also seem a bit scarce. Typemock Racer just popped up so I'll be looking at that. Anything beyond this?  Real-life opinions about tools you've used are appreciated.
119341
I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve. int firstNumber; string sign; int secondNumber; int answer;  Console.WriteLine(&quot;Input Number:&quot;); firstNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  Console.WriteLine(&quot;Input Sign:&quot;); sign = Console.ReadLine(); Console.Clear();  Console.WriteLine(&quot;Input Second Number:&quot;); secondNumber = Convert.ToInt32(Console.ReadLine()); Console.Clear();  switch (sign) {     case &quot;+&quot;:         answer = firstNumber + secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;-&quot;:         answer = firstNumber - secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;*&quot;:         answer = firstNumber * secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     case &quot;/&quot;:         answer = firstNumber / secondNumber;         Console.WriteLine(answer);         Console.ReadKey();     break;     default:         Console.WriteLine(&quot;Invalid Input&quot;);     break; }
73382
While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:  static private List&lt;int&gt; a = new List&lt;int&gt;() { 0 }; static private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] };   Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this?  Edit: (re: Panos) In a file lexical order seems to be king? what about across files?  In looking I tried a cyclical dependency like this:  static private List&lt;int&gt; a = new List&lt;int&gt;() { b[0] }; static private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] };   and the program didn't run the same (the test suit failed across the board and I didn't look further).
32163
Is there an easy way in C# to create  for a number? For example:   1 returns 1st 2 returns 2nd 3 returns 3rd ...etc   Can this be done through String.Format() or are there any functions available to do this?
79098
I have never done this type of question (with arbitrary variables in a counting problem), so I had a lot of difficulty. Please let me know if my approach is wrong. Thanks!   "Computer number 1 is assigned no jobs"; "Computers number 1 and 2 are assigned no jobs"; "exactly two of the computers are assigned no jobs" "No computer is assigned more than one job".   Here are my attempts:  Firstly, the total number of combinations is $r^n$, since for each of the n computers, an unlimited number of tasks from r can be allocated.    Since Computer 1 can be assigned no jobs, there are $r^{n-1}$ ways to assign the tasks to the remaining tasks. Thus P = $\frac{r^{n-1}}{r^n}$. Same idea to the one above, P = $\frac{r^{n-2}}{r^n}$ There are $r^{n-2}$ resources to allocate, but since any two computers, there would be $n \choose 2$ different ways to choose the two computers. Thus $P=\frac{(r^{n-2}) {n \choose 2}}{r^n}$ This one I have no idea how to even begin. Please help!
30627
In C# the Main class has string[] args parameter.  What is that for and where does it get used?
122495
I cannot figure out how to make a C# Windows Form application write to a textbox from a thread.  For example in the Program.cs we have the standard main() that draws the form:  static void Main() {     Application.EnableVisualStyles();     Application.SetCompatibleTextRenderingDefault(false);     Application.Run(new Form1()); }   Then we have in the Form1.cs:  public Form1() {     InitializeComponent();      new Thread(SampleFunction).Start(); }  public static void SampleFunction() {     while(true)         WindowsFormsApplication1.Form1.ActiveForm.Text += "hi. "; }   Am I going about this completely wrong?  UPDATE  Here is the working code sample provided from bendewey:  public partial class Form1 : Form {     public Form1()     {         InitializeComponent();         new Thread(SampleFunction).Start();     }      public void AppendTextBox(string value)     {         if (InvokeRequired)         {             this.Invoke(new Action&lt;string&gt;(AppendTextBox), new object[] {value});             return;         }         textBox1.Text += value;     }      void SampleFunction()     {         // Gets executed on a seperate thread and          // doesn't block the UI while sleeping         for(int i = 0; i&lt;5; i++)         {             AppendTextBox("hi.  ");             Thread.Sleep(1000);         }     } }