-1

I cannot set a string value of Name method of Thread array object watek[i]. Visual throws an exeption: "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

            int watki;
            string watki2;

            Console.WriteLine("Ile watkow uruchomic?: ");
            watki2 = Console.ReadLine();
            watki = Convert.ToInt32(watki2);
            Thread[] watek = new Thread[watki];

        for (int i = 0; i < watki; i++)
        {

            watek[i].Name = Convert.ToString(i);

            watek[i] = new Thread(() => Program.Watek(watek[i].Name, watki));
        }

My question is: is it even posible? And if yes, what am I doing wrong?

  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – dymanoid Mar 21 '19 at 13:48
  • 2
    You are creating an array of `watki` length, and then trying to assign the name before creating the new thread. Try flipping the two lines in your for loop - create the thread, and _then_ assign it a name. – reZach Mar 21 '19 at 13:49

2 Answers2

0

Try this.

You can't assign a property on an object before first instantiating that object.

for (int i = 0; i < watki; i++)
{
    watek[i] = new Thread(() => Program.Watek(Convert.ToString(i), watki));
}
reZach
  • 7,573
  • 10
  • 48
  • 90
0

Use object initialization:

for (int i = 0; i < watki; i++)
{
    string name = i.ToString();
    watek[i] = new Thread(() => Program.Watek(name, watki)) { Name = name };
}
Zer0
  • 6,898
  • 1
  • 18
  • 34