-2

I'm aware there is a similar question: What's the difference between struct and class in .NET?

but mine is more specific to my situation so I'd appreciate if I could get an answer. I have a class to represent some type and when I'm trying to set an array of this class values it spits null reference exception but when I use a struct it doesn't. I need to use a class due to another limitation how can I make this happen?

my c# code in a nutshell:

public class Person
{
    public string name;
    public string imageLocation;
    public string location;

    public Person()
    {
        name = "";
        imageLocation= "";
        location = "";

    }
}

in another class in the same namespace:

        int i = 0;
        Person[] people = new people[applicablePeople];
        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read() && i < applicablePeople)
            {
                people[i].name= dr["Name"].ToString();
                people[i].imageLocation= dr["ImageLocation"].ToString();
                people[i].location = dr["Location "].ToString();
                i++;
            }
        }

thnx in advance

Noam Yizraeli
  • 4,446
  • 18
  • 35
  • 2
    `Person[] people = new people[applicablePeople];` array initialization, you also need to create the object of Person Class for each item in array. It is not required in case of struct to create/ allocate the memory because they are reference type – Vikas Gupta Apr 15 '19 at 16:56

1 Answers1

2

In you example, people[i] is never initialized.

The difference is the default value for class is null while a struct cannot be null. Your default struct Person is already allocated. While a class is just a pointer to null until you initialize it.

You need to do

while (dr.Read() && i < applicablePeople)
{
    people[i] = new Person()
    // ...
Justin Lessard
  • 10,804
  • 5
  • 49
  • 61