-3

I am new to c#, I try to check if array with a customized class could work. As you see in my code, First Try is OK, but Second Try is NG. Thanks a lot if someone show me a way to solve it.

static void Main(string[] args)
{
    #First Try OK
    string[] a = new string[2];
    a[0] = "Jordan";
    a[1] = "Pippen";

    Console.WriteLine(String.Join(",", a));

    #Second Try NG
    player[] b = new player[2];
    b[0].name = "Jordan";   ==>  Object reference not set to an instance of an object
    b[1].name = "Pippen";

    Console.WriteLine(String.Join(",", b));
}
class player
{
    public string name;
}

I except I can know more detail about array concept.

Julian
  • 5,290
  • 1
  • 17
  • 40
  • C# classes and property/field names are Pascal-case, not camel-case. You should adopt the framework standards. – Enigmativity Jan 01 '23 at 02:52
  • When you see "Object reference not set to an instance of an object" it means you have an uninitialized object. In this case it is your class that was not created yet. – D. Haskins Jan 01 '23 at 07:26

1 Answers1

2

this code

#Second Try NG
player[] b = new player[2];

only creates an empty array of size 2. You need to create the player objects too

#Second Try NG
player[] b = new player[2];
b[0] = new player();
b[1] = new player();
b[0].name = "Jordan";   ==>  Object reference not set to an instance of an object
b[1].name = "Pippen";
Julian
  • 5,290
  • 1
  • 17
  • 40
pm100
  • 48,078
  • 23
  • 82
  • 145