1

First of all, sorry if I make mistakes with english, it's not my monthertongue.

I'm developing in C#, and I have a problem I don't know how to solve.

"An unhandled exception of type 'System.NullReferenceException' occurred in AccountManagement.exe"

"Additional information: La référence d'objet n'est pas définie à une instance d'un objet." Translation --> Object reference is not set to an object

Here is the code:

 private List<String> MyLines;
        public List<String> GetMyLines()
        {
            return MyLines;
        }
        public void SetOneLines(string LineToInsert) //Insert juste un élément dans ma liste
        {
            MyLines.Add(LineToInsert); !!!!! Where the error occurs !!!!
        }

This function is called here:

public void Identification()
        {
            Console.WriteLine("Indiquez votre nom et votre prénom");
            string UserLastNameTemp = Console.ReadLine();
            string UserNameTemp = Console.ReadLine();

            using (StreamReader ReadFileUser = new StreamReader("C:\\Users\\XXX\\Desktop\\user.txt"))
            {
                string Line;
                while ((Line = ReadFileUser.ReadLine()) != null)
                {
                        Console.WriteLine(Line);
                        SetOneLines(Line);
                }

            }

I already faced this type of error, but I must admit I don't know how to proceed here, cause I don't even know why this error is :D

Could someone give me a tip?

Itération 122442
  • 2,644
  • 2
  • 27
  • 73
  • 1
    Please mark the answer that helped you the most (or the earliest answer) as the accepted answer by pressing the green check mark on it's left. – Visual Vincent Apr 16 '16 at 18:47

2 Answers2

5

You need to initialize your List before adding to it.

private List<String> MyLines = new List<String>();
David Spence
  • 7,999
  • 3
  • 39
  • 63
0

You have not initialized the List in your method body. Please make sure you initialize the list like this way. Initialization will allocate memory to reference it.

private List<String> MyLines=new List<String>();
    public List<String> GetMyLines()
    {

        return MyLines;
    }

And this will return only empty list of strings.

error_handler
  • 1,191
  • 11
  • 19