Interesting Warnings Generate from VS 2005 Code Analysis
In a recent Code Review I came across two interesting warnings generated by the VS2005 Code Analysis tool that I was not aware but I think it is worth mentioning.
Typically when I have wanted to compare two string but I am concerned about the case I would take the two string and call the .ToLower() function to make them all the same case. This is actually not a good approach because strings are immutable(meaning they cannot change once created) so when call the .ToLower function you are essentially creating another string in memory which impacts performance. Instead, call the .Compare() or .Equal() functions which can do case insensitive comparisons.
To test this:
/// <summary>
///A test for StringCompareNew (string, string)
///</summary>
[TestMethod()]
public void StringCompareNewMatchTest()
{
CompareStrings target = new CompareStrings();
string string1 = "AAA";
string string2 = "aaa";
bool expected = true;
bool actual;
actual = target.StringCompareNew(string1, string2);
Assert.AreEqual(expected, actual, "Extensibility.Domain.StringComparer.StringCompareNew did not return the expected ");
}
Here is the method to test:
public class CompareStrings
{
public bool StringCompareNew(string string1, string string2)
{
if ( string.Compare(string1, string2, true) == 0 )
return true;
else return false;
}
Just remember to put add the true as one of the parameters to turn off case sensitivity.
Another approach is you can call the Equals() function:
if (string1.Equals(string2, StringComparison.CurrentCultureIgnoreCase))
return true;
else return false;
Another warning that came up that I do a lot which apparently is not correct is using the “static readonly” modifier instead of the “const” modifier for values that do not change.
This is slower:
public static readonly string String1 = "AAA";
This is faster:
public const string String2 = "aaa";
The moral of the story is that if you are programming in a VS 2005 project then turn on Code Analysis (the two biggies are “Performance Rules” and “Maintainability Rules”) and see what warnings are generated. It helps in writing better code and it is also a good learning tool. You can turn it on by going to the project properties and clicking on the Code Analysis tab. You can also select which rules you want to check which is good in weeding out the less important warnings.
Here is the knowledge base on these two rules:
http://msdn2.microsoft.com/en-us/library/ms182266(VS.80).aspx
http://msdn2.microsoft.com/en-us/library/ms182280(VS.80).aspx
0 Comments:
Post a Comment
<< Home