Click here to Skip to main content
15,882,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I run code analysis I get CA1820 and wanted to see if there are better options for writing the following block of code.


C#
if (dataFileLine.Length == NUM_COLUMNS)
{
     if (dataFileLine[10].Trim() == string.Empty
     || dataFileLine[15].Trim() == string.Empty
     || dataFileLine[21].Trim() == string.Empty
     || dataFileLine[32].Trim() == string.Empty)
     continue;
}



Gary
Posted
Comments
DamithSL 9-Jun-14 23:00pm    
what if all file lines having spaces( not empty), is it valid?

This is a performance suggestion by code analysis...
The idea is to use IsNullorEmpty() method instead of == Empty.
In your case:
C#
if (string.IsNullOrEmpty(dataFileLine[10])
  || string.IsNullOrEmpty(dataFileLine[15])
  || string.IsNullOrEmpty(dataFileLine[21])
  || string.IsNullOrEmpty(dataFileLine[32])

For reference - http://msdn.microsoft.com/en-us/library/ms182279.aspx[^]
 
Share this answer
 
v2
It's telling you to check for an empty string by checking its Length, not comparing it to the reference of String.Empty.
if (dataFileLine[10].Trim().Length == 0
    || dataFileList[15].Trim().Length == 0
....

The tiny little problem with that is if any of those dataFileLine[] references returns null the call to Trim will fail with a "Object not set to an instance of an object" error.
 
Share this answer
 
v2
Comments
Kornfeld Eliyahu Peter 9-Jun-14 16:08pm    
I didn't got you. If string is null any non static property/method - including Length - will fail with null reference exception. The code you propose here will fail on Trim() if dataFileLine[n] is null...
We deal here with a code analysis message that badly phrased...
Prgx 9-Jun-14 18:55pm    
Thank you for explaining this, I will use your suggestion and provide feedback.
I also agree,the code analysis phrase needs improvement.

Gary

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900