Test for empty strings using string length Comparing strings - TopicsExpress



          

Test for empty strings using string length Comparing strings using the System.String.Length property or the System.String.IsNullOrEmpty(System.String) method is significantly faster than using Equals. This is because Equals executes significantly more MSIL instructions than either IsNullOrEmpty or the number of instructions executed to retrieve the Length property value and compare it to zero. You should be aware that Equals and Length == 0 behave differently for null strings. If you try to get the value of the Length property on a null string, the common language runtime throws a System.NullReferenceException. If you perform a comparison between a null string and the empty string, the common language runtime does not throw an exception; the comparison returns false. Testing for null does not significantly affect the relative performance of these two approaches. When targeting .NET Framework 2.0, use the IsNullOrEmpty method. Otherwise, use the Length == comparison whenever possible. How to Fix Violations To fix a violation of this rule, change the comparison to use the Length property and test for the null string. If targeting .NET Framework 2.0, use the IsNullOrEmpty method. When to Exclude Warnings It is safe to exclude a warning from this rule if performance is not an issue.
Posted on: Sun, 09 Jun 2013 13:15:13 +0000

Trending Topics



Recently Viewed Topics




© 2015