0
int count = 0;

foreach (string s in Settings.Default.Name)
{
    count++;
}

Settings.Default.Name[count] = tb_add_name.Text;
Settings.Default.Save();

Settings.Default.Name is an empty string array but should the foreach - method just dont start if the string array is empty instead of giving me this error?

The array will be filled with words later.

Codor
  • 17,447
  • 9
  • 29
  • 56
Julian
  • 67
  • 9
  • Settings.Default.Name and empty array so how foreach interate over it, it should throw NullRefferenceException – Mostafiz Aug 11 '16 at 06:33
  • 1
    There are two possible causes for a `NullReferenceException` here: Either `Settings.Default.Name` is null (which would mean that it is *not* an empty string array), or `tb_add_name` is null. The error stack trace will tell you which of these it is. – poke Aug 11 '16 at 06:42

2 Answers2

2

Yes, but that won't change the fact that count is still 0 and you still execute Settings.Default.Name[count] = tb_add_name.Text;

So you should still check if the index is Valid or null. Something like:

if(Settings.Default.Name != null && Settings.Default.Name.Count > 0)

By the way, your method will always lead to an IndexOutOfRange exception because your foreach loop basically sets your count variable to the size of the Array, and Array[Array.Length] is always out of range.

TheCodingDamian
  • 443
  • 2
  • 12
  • You can iterate an empty enumerable, so there is nothing wrong with the count being zero. However, OP’s code will still fail because after the loop, `count` has the value `Settings.Default.Name.Count` (i.e. one more than the last index), and you can’t set values outside of the index range. You would need to actually `Add` an element (for which you don’t even need the index). – poke Aug 11 '16 at 06:38
  • I tried the Code but "Settings.Default.Name.Count > 0" doesnt work i get the error: Operator '>' cannot be applied to operands of type 'method group' and 'int' – Julian Aug 11 '16 at 07:12
  • Oh and now i get the error NullReferenceException here: 'Settings.Default.Name[count] = tb_add_Name.Text' But 'count' is 0 and 'tb_add_Name.Text' is not empty or null – Julian Aug 11 '16 at 07:17
  • Are you sure that `tb_add_Name` and Settings.Default are both not null? If yes, what is the size of Settings.Default.Name when you execute that line? – TheCodingDamian Aug 11 '16 at 09:46
0

You can use Array Length property.

if(Settings.Default.Name.Count > 0)
{
    int count = 0;

    foreach (string s in Settings.Default.Name)
    {
        count++;
    }

    Settings.Default.Name[count] = tb_add_name.Text;
    Settings.Default.Save();
}
Kalu Singh Rao
  • 1,671
  • 1
  • 16
  • 21