Why do I get a NullReferenceException in this foreach method [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
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.

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.

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();
}

Related

Why Can I Not Assign Integers to an Array With This ForEach Loop ('Object Reference Not Set' Exception Thrown) [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I am trying to convert integers (I got the integers from converting characters to their ascii codes) into an array of integers but when I run the program I get an error that says "Object Reference Not Set to an Instance of an Object" and it is referring to the last line in the code. What am I doing wrong here?
Thank you for any input, I am relatively new.
foreach (char letter in arReverse)
{
int count = -1;
count = count + 1;
int num = (System.Convert.ToInt32(letter + 5));
Console.Write(System.Convert.ToInt32(letter + 5));
Console.Write(" ");
arNum[count] = num;
}
I get an error that says "Object Reference Not Set to an Instance of an Object" and it is referring to the last line in the code.
...
What am I doing wrong here?
arNum[count] = num; may not be initialized.
Make sure the array/list arNum is initialized. This is done with the new keyword such as
var arNum = new List<int>();
var arNum = new int[arReverse.Length];

How I can get elements from dictionary and add into array? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
I have IDictionary<string, int>. I need to get keys and values from dictionary in string format and add into string[] array. I need to do it because I want to pass that text in function and that function takes string array.
I have that code for getting value:
foreach (KeyValuePair<string, int> kvp in dict)
{
dataList.Add(kvp.Key + " " + kvp.Value.ToString());
}
I've created list and add in that list keys and values. After I was thinking to create for loop and from list add elements into array, but have error. Loop:
string[] txtArr;
for (int i = 0; i < dataList.Count; i++)
{
txtArr[i] = dataList[i];
}
Error: System.NullReferenceException. I don't understand where is the problem. From what I read about that error, I understood it raised because something is null. But if I'm trying print in console dictionary or list all is OK, there isn't null, also i is int and = 0. Where is the problem?
Your array is not instantiated, dude:
string[] txtArr = new string[dataList.Count];
for (int i = 0; i < dataList.Count; i++)
{
txtArr[i] = dataList[i];
}
or you can do it like this:
string[] txtArr = dataList.ToArray();
or you can do it like this:
string[] txtArr = dict.ToList().Select(x => x.Value).ToArray();
You have to initialize the string array.
string[] txtArr = new string[dataList.Count];

C# RemoveAt from list one item at a time [duplicate]

This question already has answers here:
Collection was modified; enumeration operation may not execute
(16 answers)
Closed 4 years ago.
I am trying to remove one item from the list until the list is empty. My code only successfully removes one item from the list and then cause an error. How do I fix this?
public void ReleaseAllAnimals()
{
int i = 0;
foreach (var value in _farmAnimals)
{
_farmAnimals.RemoveAt(i);
Console.WriteLine(value.Species());
i++;
}
}
You should not be modifying the collection while enumerating it. As you want to remove elements you should use for loop instead with indexer so that you do not face the issue.
You can loop through the list in reverse order like and remove from the end item one by one:
for(int i=_farmAnimals.Count -1; i >= 0; i--)
{
var species = _farmAnimals[i].Species(); // get species of current item
_farmAnimals.RemoveAt(i); // remove from list
Console.WriteLine(species); // display it
}
You can remove each item from the first of your List by using RemoveAt(0)
Change your code to this:
int size = _farmAnimals.Count;
for(int i = 0; i < size; i++)
{
var s = _farmAnimals[0].Species();
Console.WriteLine(s);
_farmAnimals.RemoveAt(0);
}
I hope it helps you

Better way to have foreach loop iteration tracking integer value incrementing [duplicate]

This question already has answers here:
Convert an array to dictionary with value as index of the item and key as the item itself
(3 answers)
Closed 7 years ago.
is there any better way of this code
var dictionary= new Dictionary<int,object>();
int x=0;
foreach( var item in SomeCollection)
{
x++;
dictionary.Add(x,item);
}
Whats the best practice ? Can we avoid declaring int x=0; and get the current iteration value ??
Certainly a for loop. Optionally you could use LINQ:
int temp = 0;
var dict = SomeCollection.ToDictionary(_ => ++temp, item => item);

System.NullReferenceException Object reference not set to an instance of an object. at i++ [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I'd like to read every 2nd variable from result[] to questions.
string[] questionstr = null;
int ii = 0;
for (int i = 0; result.Length > i;)
{
questionstr[ii] = result[i];
ii = ii+1;
i = i+2;
}
it gives me System.NullReferenceException at ii=ii+1; I tried ii++; too but same error.
Your NullReferenceException must be from the line above:
questionstr[ii] = result[i];
Your array questionStr isn't initialized. Trying to use it is causing the exception.
You should initialize it before using it, like this:
string[] questionStr = new string[result.Length];
so that the array size is large enough to hold all your results
You have to initialize the string array questionstr as following:
var questionStr = new string[result.Length/2+1];

Categories

Resources