0

How to assign values to objects in foreach loop. Code is below:

using System;

namespace WorkingWithClasses
{
    class Program
    {
        static void Main(string[] args)
        {
        //create 5 player objects
        Player[] players = new Player[5];
        //assigning a value to a player brings null reference exception error:
        foreach(Player player in players)
        {
            player.Skill = 5;
        }


        float skillSum = 0;
        foreach(Player player in players)
        {
            skillSum += player.Skill;
        }

        Console.WriteLine(skillSum);
    }
}
class Player
{
    public float Skill { get; set; }
}
}
  • 1
    Welcome to Stack Overflow. Unfortunately your question is not clear - it's *just* code apart from the title. Even the comment doesn't say *what* exception you're receiving. I suspect it's a NullReferenceException, in which case you should read https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it. For more guidance on asking a good Stack Overflow question, please read https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ – Jon Skeet Jan 03 '20 at 06:47
  • What exception error ur getting. Try to assign `5.0F` like that – sri harsha Jan 03 '20 at 06:50
  • 2
    @sriharsha: There's an implicit conversion from `int` to `float` - that isn't the problem. – Jon Skeet Jan 03 '20 at 07:02

2 Answers2

3

Every "Player" in your players array is not initialized. Try with this for loop instead of the foreach loop where you are getting the null reference:

for (var i = 0; i < players.Length; i++)
{
    players[i] = new Player() { Skill = 5 };
}

You can also use this, however it's slower than iterating through the array with a for loop:

using System.Linq;

players = Enumerable.Repeat(new Player() { Skill = 5 }, 5).ToArray();
Ignasi93
  • 533
  • 2
  • 5
  • 14
0

You need to initialize your players instance object since you are creating array holder.

Replace Player[] players = new Player[5]; with

Player[] players = Enumerable.Repeat(new Player(), 5).ToArray();

Turbot
  • 5,095
  • 1
  • 22
  • 30