I have some application that passes a string parameter to a method that is invoked using a thread inside a loop like this, this thread is create 50 times  Thread t = new Thread(new ThreadStart(() =&gt; {     StartExtraction( savedFileName); })); t.Name = "do"; t.Start();   in the StartExtraction method I noticed that the parameters are overwritten , I mean if the first invocation was with savedFileName="abc" and the second was with savedFilename="xyz" ,the method always processes "xyz", I mean  StartExtraction when debugged, the parameter is overwritten, , why?
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?
77422
I have a call to a method in a class as follows:  String key1 = "test1"; String key2 = "test2";  long[] datalr = new long[] {}; datalr = TestClass.callerSub(key1,key2);   The test class is as follows:  public class TestClass {  Public TestClass { }  public long[] callerSub(string key1, String key2){  long[] datalr = new long[] {0,0};  datalr[0] = 2; datalr[1] = 3;  return datalr;  } }   I'm getting the following error in the first class:  Error: Compile Error: Method does not exist or incorrect signature: TestClass.callerSub(String, String) at line 54 column 12       which is the following line:  datalr = TestClass.callerSub(key1,key2);   The datalr data in the callerSub method is just an example above,  Any idea why?  Thanks
75990
We have to build Strings all the time for log output and so on. Over the JDK versions we have learned when to use StringBuffer (many appends, thread safe) and StringBuilder (many appends, non-thread-safe).  What's the advice on using String.format()? Is it efficient, or are we forced to stick with concatenation for one-liners where performance is important?  e.g. ugly old style,  String s = "What do you get if you multiply " + varSix + " by " + varNine + "?";   vs. tidy new style (String.format, which is possibly slower),  String s = String.format("What do you get if you multiply %d by %d?", varSix, varNine);   Note: my specific use case is the hundreds of 'one-liner' log strings throughout my code. They don't involve a loop, so StringBuilder is too heavyweight. I'm interested in String.format() specifically.
10972
I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield.  I'd like to ask how people have gone about testing code that relies on threads for successful execution, or just how people have gone about testing those kinds of issues that only show up when two threads interact in a given manner?  This seems like a really key problem for programmers today, it would be useful to pool our knowledge on this one imho.
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
70264
If I have a method such as:  public void MyMethod(int arg1, string arg2)   How would I go about getting the actual names of the arguments? I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.  I would like to write a method which looks like this:  public static string GetParamName(MethodInfo method, int index)   So if I called this method with:  string name = GetParamName(MyMethod, 0)   it would return "arg1". Is this possible?
37596
Say I have a class that's meant to perform a single function. After performing the function, it can be destroyed. Is there any reason to prefer one of these approaches?  // Initialize arguments in constructor MyClass myObject = new MyClass(arg1, arg2, arg3); myObject.myMethod();  // Pass arguments to method MyClass myObject = new MyClass(); myObject.myMethod(arg1, arg2, arg3);  // Pass arguments to static method MyClass.myMethod(arg1, arg2, arg3);   I was being intentionally vague about the details, to try to get guidelines for different situations. But I didn't really have in mind simple library functions like Math.random(). I'm thinking more of classes that perform some specific, complex task, but only require one (public) method to do it.
121911
I'm seeing some wierd behaviour when throwing exceptions and catching them in the Application.ThreadException event handler.  Basically whats happening in the sample below is that an exception is thrown in the DoWork event handler of a BackgroundWorker. The RunWorkerCompleted event handler rethrows a new exception with the original as the inner exception.  Why does the inner exception show up in the ThreadException event handler and not the acutal exception being thrown? If I do not provide an inner exception in the RunWorkerCompleted event handler, the correct exception will show up.  using System; using System.Windows.Forms; using System.ComponentModel;  namespace WierdExceptionApp {     class WierdExceptionForm : Form     {         BackgroundWorker worker = new BackgroundWorker();          public WierdExceptionForm()         {             worker.DoWork += new DoWorkEventHandler(worker_DoWork);             worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);             worker.RunWorkerAsync();         }          void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)         {             if (e.Error != null)             {                 throw new Exception("worker_RunWorkerCompleted", e.Error);             }         }          void worker_DoWork(object sender, DoWorkEventArgs e)         {             throw new Exception("worker_DoWork");         }          [STAThread]         static void Main()         {             Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);             Application.Run(new WierdExceptionForm());         }          static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)         {             MessageBox.Show(e.Exception.Message);         }    } }
117969
I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.  However, I was looking through System.Web.Security.Membership using Reflector and found code like this:  public static class Membership {     private static bool s_Initialized = false;     private static object s_lock = new object();     private static MembershipProvider s_Provider;      public static MembershipProvider Provider     {         get         {             Initialize();             return s_Provider;         }     }      private static void Initialize()     {         if (s_Initialized)             return;          lock(s_lock)         {             if (s_Initialized)                 return;              // Perform initialization...             s_Initialized = true;         }     } }   Why is the s_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? Are reads and writes of variables atomic?
12512
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.  If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.  How can I do something like that?  PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.
18012
I have a single string that contains the command-line parameters to be passed to another executable and I need to extract the string[] containing the individual parameters in the same way that C# would if the commands had been specified on the command-line. The string[] will be used when executing another assemblies entry-point via reflection.  Is there a standard function for this? Or is there a preferred method (regex?) for splitting the parameters correctly? It must handle '"' delimited strings that may contain spaces correctly, so I can't just split on ' '.  Example string:  string parameterString = @"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam foo";   Example result:  string[] parameterArray = new string[] {    @"/src:C:\tmp\Some Folder\Sub Folder",   @"/users:abcdefg@hijkl.com",   @"tasks:SomeTask,Some Other Task",   @"-someParam",   @"foo" };   I do not need a command-line parsing library, just a way to get the String[] that should be generated.  Update: I had to change the expected result to match what is actually generated by C# (removed the extra "'s in the split strings)
121
I always thought Java uses pass-by-reference. However, I've seen a couple of blog posts (for example, ) that claim that it isn't (the blog post says that Java uses pass-by-value). I don't think I understand the distinction they're making. What is the explanation?
119860
A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be &quot;reset&quot; on each iteration. Could someone explain why they would not be)? (My first question, really looking forward to the responses.) The example below is obviously not the code in question but reflects the scenario:  Please excuse the code example, it looks fine in the editor preview?? for (int i =0; i&lt; 10; i++) {     decimal? testDecimal;     string testString;      switch( i % 2  )     {         case 0:         testDecimal = i / ( decimal ).32;         testString = i.ToString();             break;         default:             testDecimal = null;             testString = null;             break;     }      Console.WriteLine( &quot;Loop {0}: testDecimal={1} - testString={2}&quot;, i, testDecimal , testString ); }   EDIT: Sorry, had to rush out for child care issue. The issue was that the prod code had was that the switch statement was huge and in some &quot;case&quot;'s a check on a class' property was being made, like if (myObject.Prop != null) then testString = myObject.Stringval... At the end of the switch, (outside) a check on testString == null was being made but it was holding the value from the last iteration,hence not being null as the coder assumed with the variable being declared within the loop. Sorry if my question and example was a bit off, I got the phone call about the day care as I was banging it together. I should have mentioned I compared IL from both variables in and out the loop. So, is the common opinion that &quot;obviously the variables would not be reinitialized on each loop&quot;? A little more info, the variables WHERE being initialized on each iteration until someone got over enthusiastic with ReSharper pointing out &quot;the value is never used&quot; and removed them.  EDIT: Folks, I thank you all. As my first post I see how much clearer I should be in the future. The cause of our unexpected variable assignment can me placed on an inexperienced developer doing everything ReSharper told him and not running any unit tests after he ran a &quot;Code Cleanup&quot; on an entire solution. Looking at the history of this module in VSS I see variables Where declared outside of the loop and where initialized on each iteration. The person in question wanted his ReSharper to show &quot;all green&quot; so &quot;moved his variables closer to assignment&quot; then &quot;Removed redundant assignment&quot;! I don't think he will be doing it again...now to spend the weekend running all the unit tests he missed! How to do mark a question as answered?
14089
I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:  public void myFunction(ref MyClass someClass)   and  public void myFunction(out MyClass someClass)   Which should I use and why?
75825
I have created a program which searches for files in a source folder. If it finds any file, it processes that file and moves it to a destination folder, then looks for a new file in the source folder. It has to keep on checking the source folder for a file.  I have used a thread to look for files in the source folder. The problem I am facing is whenever any exception is thrown during file processing, the thread gets stopped. I want the thread to be running even if an exception is thrown. It has to move the file that caused the error to some other folder and look for a new file in the source folder. How can I make the thread keep on running?  Eg:  public void run() {     try {         searchfile();     }     catch(Exception e) {         e.printStackTrace();     } }  public void searchfile(){   ... }     Update :   I should be more clear in my question. Actually there are 4 source folders and 4 destination folders. I have to perform the same operation in each source &amp; destination pair. So i have created 4 threads in one class and do the operation in separate class.  class MainClass {    public static void main(String[] args){       for(int i=0;i&lt;4;i++){          SearchClass search = new SearchClass();          Thread thread = new Thread(search);          thread.start();      }    }    }  class SearchClass {    public void run() {    try {       searchfile();    } catch(Exception e) {       e.printStackTrace();    } }  public void searchfile(){ ... } }   All the thread wont stop running eventhough it caught any exception in middle. How can i do that?
80489
There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.  First type:  List&lt;string&gt; someList = &lt;some way to init&gt; foreach(string s in someList) {    &lt;process the string&gt; }   Other Way:  List&lt;string&gt; someList = &lt;some way to init&gt; someList.ForEach(delegate(string s) {     &lt;process the string&gt; });   I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...
92088
public class WrapperTest {      public static void main(String[] args) {          Integer i = 100;         Integer j = 100;          if(i == j)             System.out.println("same");         else             System.out.println("not same");     }     }   The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.