I read alot about generic lists and the reasons for NullReferenceExceptions, but in my case it looks like I've done everything right, but still get the famous error.
I initialize a generic List at the top of a class:
List<CustomType> customTypes = new List<CustomType>();
then I add some items to the list and of course I debug the count and names to make sure there is no null entry. Without touching the list any further, I call this method:
string newString = GetString("some string", customTypes);
Its structure looks like this:
public string GetString(string value, List<CustomType> cTypes)
{
// in my case I add two items to the customTypes list, when the form is loaded
Console.WriteLine(customTypes.Count); // output: 2
Console.WriteLine(cTypes.Count); // output: 2
foreach(CustomType ct in cTypes)
{
// All I do within this foreach is just debugging
Console.WriteLine("Current item: " + ct.ToString()); // NullReferenceException ct seems to be null
}
return value;
}
I don't know why it is throwing an error. Any idea?
EDIT: Actually the first thing in the foreach loop is: Console.WriteLine("Current item: " + ct.ToString())
// which throws the error and tells me that ct is null, but how can this be? The console shows me that there are items in both lists?!