0

I am using a class that has a member of another class (all of the members are strings), and when I try to set a value I get a null reference exception. Can anyone help me? I'm still kind of new to classes.

Here are my two classes:

    public class MergeFields
    {
        public string FNAME { get; set; }
        public string LNAME { get; set; }
        public string CITY { get; set; }
        public string STATE { get; set; }
    }


    public class Member
    {
        public string email_Address { get; set; }
        public string status { get; set; }
        public MergeFields merge_fields { get; set; }
    }

And here is where I set the value of CITY:

Member Person = new Member();
string cityTest = "New York";
person.merge_fileds.CITY = cityTest; //This is where I get the exception

Am I missing something stupid obvious? Or is this just not possible?

2 Answers2

2

Yes, you are. You have two choices:

  1. Explicit class initialization:

    person.merge_fileds = new MergeFields();

  2. Implicit class initialization:

    public class Member
    {
       public string email_Address { get; set; }
       public string status { get; set; }
       public MergeFields merge_fields { get; set; }
    
       public Member(){
          merge_fields = new MergeFields();
       }
    }
    

Using second approach allows you not to change the code for assigning.

SouXin
  • 1,461
  • 10
  • 15
1

You neeed to initialize first

person.merge_fileds = new MergeFields{CITY = cityTest}; 
Harsh
  • 3,515
  • 2
  • 21
  • 41
  • 2
    If you spend more than 5 minutes answering C# questions, you should know that anything to do with a null reference exception is a duplicate... – DavidG May 09 '18 at 16:20
  • Right, should have done that. Thanks :) – Harsh May 09 '18 at 16:21