简体   繁体   中英

Check empty element array of double c#

I'm looking for a code to check if an element of my array of double is empty. I tried with isNaN , string.isNullOrEmpty and 0.0D but nothing to do, I still have this text : Not a Number.

So, do you know any code in C# which is able to check if an element in a an array of double is empty?

Here is my code:

if (!Double.IsNaN(d1.getChiffreAffaireBase()[keyIndex1]))
{
    textBox43.Text = calcMargeCa(d1.getChiffreAffaireBase()[keyIndex1], d1.getChiffreAffairePlus()[keyIndex1]).ToString("0.00");
    textBox44.Text = calcMargeCa(d1.getChiffreAffaireBase()[keyIndex1+1], d1.getChiffreAffairePlus()[keyIndex1+1]).ToString("0.00");
}
else
{
    label13.Hide();
    textBox43.Hide();
    textBox44.Hide();
}

if you declare an array like this

double[] array = new double[12];    // elements cannot be null

all elements will be set to 0 .

Declare it as nullable , if you really want

var array = new double?[12];    // elements can be null
var isEmpty = (array[6] == null);

or

var isEmpty = !array[6].HasValue;

Value types cannot not have a value (that is to say, they cannot be null ) but you could use a Nullable<double> (or double? for short) which can be set to null if you want to indicate that it doesn't have a value. Here's an example:

double?[] array = new double?[12];

then for checking if it has a value you compare it to null :

if (array[6] == null){
    // do your thing
}

Edit:

Off topic but now that you've posted your code I see that you're using double to represent money (Chiffre d'Affaire or Revenue) while that could work, you should use decimal instead

Double.IsNaN doesn't check for null values , check this for more or read the documentations about it https://stackoverflow.com/a/7967190/6001737

instead you can use double?[] array = new double?[12]; which is Nullable and you can then check if a certain array value equals null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM