Avoid making useless new object
June 4th, 2008
You often see statements like the one here when programmers want to check if a string has value or not.
if(strName!="") { ... }
For C++ programmers (who uses CString for example) this is correct and not really unusual - but please if you’re writing code in C# or another .NET language keep in mind that this causes the allocation of a new String object just for the reason to compare it with an empty string.
Correct implementations would be:
if(strName.Length <= 0) { ... } if(strName.Length == 0) { ... }
You will not regognize this in a performance test or when using the application but it’s just good form to do it right - also because you know why you should do.
When working with CStrings it’s dispensable faster or slower to compare with an empty string or just to compare the length. If you have a look at the IsEmpty() member function of CString Class you’ll mention that I’m right:
bool IsEmpty() const throw() { return( GetLength() == 0 ); }





