0

I'm trying to add a string from a List, to another List. After getting a NullReferenceException I tried to print out the content of the string. Its NOT Null. That's Why I cant understand why I'm getting this Exception.

foreach (string s in EntrieDatasReady)
{
    if (s.Contains("["))
    {
        MessageBox.Show(s);
        CategoryList.Add(s);
        MessageBox.Show(s);
    }
}

Before Crashing the application he gives me this Output:

1

So the Exception seems to appear when I'm trying to add the string to the List. This is not understandable to me. Because obviously "s" is not "Null".

My Code:

2

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
MHerbst
  • 11
  • 1
  • 5
    _"Because obviously "s" is not "Null""_ - Why "obviously"? – ProgrammingLlama Jul 25 '22 at 09:10
  • 1
    Also you have other stuff in your code which can be null. Especially taking in account that first `MessageBox` seems to be showing =) – Guru Stron Jul 25 '22 at 09:11
  • 7
    If your test is correct, it means `CategoryList` is null. (note though, that if `s` is null, the if statement will already fail on `c.Contains` – Me.Name Jul 25 '22 at 09:11
  • CategoryList is a public List, with the Addition { get; private set; }. So maybe the Add function gives null... but why? i'm sorry for this question I'm just an apprentice since about one month. – MHerbst Jul 25 '22 at 09:18
  • 2
    @MHerbst How do you initialize that `CategoryList`? – AKX Jul 25 '22 at 09:20
  • 1
    Is it ever created? if the property is only declared, it will be null. You could have it automatically create an instance in the getter if null, or always have a default instance, e.g. `public List CategoryList { get; private set; } = new List();` – Me.Name Jul 25 '22 at 09:21
  • @AKX public List CategoryList { get; private set; } – MHerbst Jul 25 '22 at 09:22
  • 1
    @Me.Name OMG thank you so much. I'm just so stupid. forgot the = new List function. – MHerbst Jul 25 '22 at 09:24
  • @AKX unfortunately it just showed me that message. It didnt reffered to any Code. – MHerbst Jul 25 '22 at 11:10
  • Then you didn't use the debugger correctly. It will definitely show you the line where the exception happens, and you can use its tools to view variable values. – AKX Jul 25 '22 at 11:12
  • Im trying my best to learn, I'm just a beginner programming in this company for like 2 weeks. Thabks for your help :) – MHerbst Jul 25 '22 at 16:05

0 Answers0