0

I have a class that only has public automatic properties of strings like Name, ID, LastName and also I have defiend a constructor for it and defiend them as string.Empty too. Now in the code I create an array of this class like this:

AlternateAddressSummary[] alternateAddressSummaries = new AlternateAddressSummary[6];
int adrsCounter = -1;
foreach (Addresses adrs in address_alternative)
{
    adrsCounter++;
    FillAlternateAddressSummaryObject(alternateAddressSummaries[adrsCounter], adrs);
}

And FillAlternateAddressSummaryObject is just filling the properties of each object for example:

private void FillAlternateAddressSummaryObject(AlternateAddressSummary alA, Addresses adrs)
{
    alA.AlternateAdressLine1 = adrs.City;
    //...
}

But why do I get NULL exception on alA? Even when I create those 6 array objects, they are initialized to NULL. Shouldn't they be set to what I say in the constructor?

John Saunders
  • 157,405
  • 24
  • 229
  • 388
  • show all relevant code please as well as how you were setting items to string.Empty.. also are you familiar with how to use `FormatterServices.GetUninitializedObject` Method and from there you can write your own little class to set the null initial values to string.Empty as well – MethodMan Nov 04 '14 at 18:17
  • 2
    You are not creating 6 objects in an array. You are creating 6 references to objects and references default to null. You still need to create the objects by invoking the constructor. – Mike Zboray Nov 04 '14 at 18:17
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Nov 04 '14 at 18:20

1 Answers1

3

That's because you didn't instantiate any of the members of alternateAddressSummaries

what you did is kinda like doing this

AlternateAddressSummary1;
AlternateAddressSummary2;
AlternateAddressSummary3;
...

You've declared an array of AlternateAddressSummary, but you haven't actually instantiated any of them. they're still all null


if you did this

for(int i=0; i<alternateAddressSummaries.Length; i++)
{
    alternateAddressSummaries[i]= new AlternateAddressSummary(/*params*/);
}

they would be instantiated and their values would be whatever your constructor set them to.

John Saunders
  • 157,405
  • 24
  • 229
  • 388