UPDATE:  Thank you all for your answers, especially pertaining to .equals().   The only detail is that the "msgCode = ..." and "msgValue = ..." statements are enough to return an empty stirngBuilder. I.e., I don't even have to declare the IF statement to make it stop working.   Any clues?  ORIGINAL: Please let me know why StringBuilder returns nothing (perhaps doesn't even work) when I include the rest of the code (besides stringBuilder.append(...)) inside the while().  When I include just stringBuilder.append(...), then there is a return value.  while ( (receiveString = bufferedReader.readLine()) != null ) {     stringBuilder.append(receiveString + "\n");      // analyze the first 3 characters in the message     String msgCode = receiveString.substring(0, 3);     Number msgValue =  Integer.parseInt(receiveString.substring(4, receiveString.length()-4));      // use IF-ELSE since SWITCH doesn't work with String     if (msgCode=="ATT") {         dataATT[2*dataATTcount+1] = msgValue;          dataATTcount++;     } else {         dataMED[2*dataMEDcount+1] = msgValue;          dataMEDcount++;                          } }   Thanks
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
75336
Someone told me it's more efficient to use StringBuffer to concatenate strings in Java than to use the + operator for Strings. What happens under the hood when you do that? What does StringBuffer do differently?
26673
Switch statement fallthrough is one of my personal major reasons for loving switch vs. if/else if constructs. An example is in order here:  static string NumberToWords(int number) {     string[] numbers = new string[]          { "", "one", "two", "three", "four", "five",            "six", "seven", "eight", "nine" };     string[] tens = new string[]          { "", "", "twenty", "thirty", "forty", "fifty",            "sixty", "seventy", "eighty", "ninety" };     string[] teens = new string[]         { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",           "sixteen", "seventeen", "eighteen", "nineteen" };      string ans = "";     switch (number.ToString().Length)     {         case 3:             ans += string.Format("{0} hundred and ", numbers[number / 100]);         case 2:             int t = (number / 10) % 10;             if (t == 1)             {                 ans += teens[number % 10];                 break;             }             else if (t &gt; 1)                 ans += string.Format("{0}-", tens[t]);         case 1:             int o = number % 10;             ans += numbers[o];              break;         default:             throw new ArgumentException("number");     }     return ans; }   The smart people are cringing because the string[]s should be declared outside the function: well, they are, this is just an example.  The compiler fails with the following error:   Control cannot fall through from one case label ('case 3:') to another Control cannot fall through from one case label ('case 2:') to another   Why? And is there any way to get this sort of behaviour without having three ifs?
19825
But here's an example:  Dim desiredType as Type if IsNumeric(desiredType) then ...   EDIT: I only know the Type, not the Value as a string.  Ok, so unfortunately I have to cycle through the TypeCode.  But this is a nice way to do it:   if ((desiredType.IsArray))       return 0;   switch (Type.GetTypeCode(desiredType))  {       case 3:       case 6:       case 7:       case 9:       case 11:       case 13:       case 14:       case 15:           return 1;  }  ;return 0;
111654
I just . Namely, the C++ function:  void returnCharPtr(char * someString, int n);   cannot return any CharPtr because the someString pointer is passed by value. Also, the intent of the author was clear:      So, another option is to pass the parameter as an argument, so you process your string in a function but don't create a new copy.   But as the change was rejected (3 vs 2) the post stayed in an incorrect state (IMHO).   I left a comment to the author. Can I argue with the editors' decision?
12823
In .NET, what is the difference between String.Empty and "", and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Empty will ensure are not a problem?
56271
C#6 Update  In :  // C#1-5 propertyValue1 = myObject != null ? myObject.StringProperty : null;   // C#6 propertyValue1 = myObject?.StringProperty;   The question below still applies to older versions, but if developing a new application using the new ?. operator is far better practice.  Original Question:  I regularly want to access properties on possibly null objects:  string propertyValue1 = null; if( myObject1 != null )     propertyValue1 = myObject1.StringProperty;  int propertyValue2 = 0; if( myObject2 != null )     propertyValue2 = myObject2.IntProperty;   And so on...  I use this so often that I have a snippet for it.  You can shorten this to some extent with an inline if:  propertyValue1 = myObject != null ? myObject.StringProperty : null;   However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:  propertyValue1 = myObject != null ?      (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;   What I really want is ?? style syntax, which works great for directly null types:  int? i = SomeFunctionWhichMightReturnNull(); propertyValue2 = i ?? 0;   So I came up with the following:  public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action, TResult valueIfNull )     where T : class {     if ( input != null ) return action( input );     else return valueIfNull; }  //lets us have a null default if the type is nullable public static TResult IfNotNull&lt;T, TResult&gt;( this T input, Func&lt;T, TResult&gt; action )     where T : class     where TResult : class { return input.IfNotNull( action, null ); }   This lets me us this syntax:  propertyValue1 = myObject1.IfNotNull( x =&gt; x.StringProperty ); propertyValue2 = myObject2.IfNotNull( x =&gt; x.IntProperty, 0);  //or one with multiple levels propertyValue1 = myObject.IfNotNull(      o =&gt; o.ObjectProp.IfNotNull( p =&gt; p.StringProperty ) );   This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.  This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:  if( ( obj1 == null &amp;&amp; obj2 == null ) ||      ( obj1 != null &amp;&amp; obj2 != null &amp;&amp; obj1.Property == obj2.Property ) )     ...  //becomes if( obj1.NullCompare( obj2, (x,y) =&gt; x.Property == y.Property )      ...   What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?    I guess what I really want here is a compiler/language extension:  propertyValue1 = myObject != null ? myObject.StringProperty : null;  //becomes propertyValue1 = myObject?StringProperty;   This would make the complex case far easier:  propertyValue1 = myObject != null ?      (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null  //becomes propertyValue1 = myObject?ObjectProp?StringProperty;   This would only work for value types, but you could return nullable equivalents:  int? propertyValue2 = myObject?ObjectProp?IntProperty;  //or  int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
31812
I use object != null a lot to avoid . What is an alternative to: if (someobject != null) {     someobject.doCalc(); }
88076
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.  Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?  /// &lt;summary&gt; /// Compare property values (as strings) /// &lt;/summary&gt; /// &lt;param name="obj"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public bool PropertiesEqual(object comparisonObject) {      Type sourceType = this.GetType();     Type destinationType = comparisonObject.GetType();      if (sourceType == destinationType)     {         PropertyInfo[] sourceProperties = sourceType.GetProperties();         foreach (PropertyInfo pi in sourceProperties)         {             if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null &amp;&amp; destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))             {                 // if both are null, don't try to compare  (throws exception)             }             else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))             {                 // only need one property to be different to fail Equals.                 return false;             }         }     }     else     {         throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");     }      return true; }
87194
I've been told that code such as:  for (int i = 0; i &lt; x.length(); i++) {     // blah }   is actually O(n^2) because of the repeated calls to x.length(). Instead I should use:  int l = x.length(); for (int i = 0; i &lt; l; i++) {     // blah }   Is this true? Is string length stored as a private integer attribute of the String class? Or does String.length() really walk the whole string just to determine its length?
70818
My question is on return values produced by this code:  if [ -n ]; then echo "true"; else echo "false"; fi   This prints true.  Its complementary test using [ -z ] also prints true:  if [ -z ]; then echo "true"; else  echo "false"; fi   In the above code, why does the [ -n ] test assume the string value that is not passed at all, as not null?  The code below prints false. This is expected since the passed string value is null and of zero length.  if [ -n "" ]; then echo "true"; else  echo "false"; fi
2552
Possible Duplicate:          I've coded something like this:  public bool IsDataChanged() {                T value1 = GetValue2;     T value2 = GetValue1();      return (valueInDB != valueFromView); }   Right now the function doesn't compile with the error "Operator '!=' cannot be applied to operands of type 'T' and 'T'". What do I have to do to make this function work ?
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?
111151
Can I simply use  if(myString == nil)   For some reason a string that I know is null, is failing this statement.
79610
an example code what I try to do will surely do better than my english:  public bool IsNumericValueInBounds (string value, Type numericType) {   double d = double.NaN;         bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d });    return inBounds; }   Unfortunately the TryParse method needs an out parameter so this doesn't work. any ideas how to solve this?  (ps.: would'nt this be a nice example for duck typing? - because i know every numericType has an "TryParse" or I am mistaken?)
22356
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?    string testString = "Test"; string anotherString = "Another";  if (testString.CompareTo(anotherString) == 0) {} if (testString.Equals(anotherString)) {} if (testString == anotherString) {}   (Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)
102402
I'm wanting to parse a string into a nullable int in C#.  ie. I want to get back either the int value of the string or null if it can't be parsed.  I was kind of hoping that this would work  int? val = stringVal as int?;   But that won't work, so the way I'm doing it now is I've written this extension method  public static int? ParseNullableInt(this string value) {     if (value == null || value.Trim() == string.Empty)     {         return null;     }     else     {         try         {             return int.Parse(value);         }         catch         {             return null;         }     } }      Is there a better way of doing this?  EDIT:  Thanks for the TryParse suggestions, I did know about that, but it worked out about the same.  I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?