-2

This is not something I don't know what is NullRefrenceException. There is some uncertain situation where I was getting the error.

I'm trying to assign values to properties of some classes.

Here are my classes.

// These classes are in EmailProcess namspace
public class ActionedEmailReport
{
    public Message Message { get; set; }
    public string SaveToSentItems { get; set; }
}

public class ToRecipient
{
    public EmailObject.EmailAddress EmailAddress { get; set; }
}

public class Message
{
    public string Subject { get; set; }
    public Body Body { get; set; }
    public List<ToRecipient> ToRecipients { get; set; }
}

public class Body
{
    public string ContentType { get; set; }
    public string Content { get; set; }
}

// Below class in EmailObject namespace.
namespace EmailObject
{
   public class EmailAddress
   {
      public string Address { get; set; }
   }
}

Here is my code to assign values to the properties of the classes.

public void EmailProcessing(string recepeint)
{
   ActionedEmailReport actionedReport = new ActionedEmailReport();
   List<ToRecipient>toRecipient = new List<ToRecipient>();
   EmailObject.EmailAddress emailAddress= new EmailObject.EmailAddress();
   emailAddress.Address = recepeint;
   toRecipient.Add(new ToRecipient()
{
   EmailAddress=emailAddress
});

   // I'm getting error on the below line.    
   actionedReport.Message.ToRecipients = toRecipient;
   actionedReport.Message.Body.Content = "Hello";
   actionedReport.Message.Body.ContentType = "Text";
   actionedReport.SaveToSentItems = "True";
   actionedReport.Message.Subject = "Demo Email"
}

On the line actionedReport.Message.ToRecipients = toRec; I am getting error that

System.NullReferenceException:Object reference not set to an instance of an object.

I have checked inputs properly and sure that I am assigning some value to toRecipient then why I am getting this error. This is driving me crazy.

Ashok
  • 1,678
  • 4
  • 33
  • 59
  • 1
    It certainly looks like `actionedReport.Message` hasn't been assigned, but running under a debugger will be able to confirm this. – Joe Apr 05 '17 at 20:52
  • `toRecipient` might not be null, but what about `Message` or `ToRecipients`? When you build a new `ActionedEmailReport`, are the objects that it contains instantiated? – pgruber Apr 05 '17 at 20:52
  • Check the question which yours is a duplicate of. Specifically the accepted answer's "Class Instances" and "Indirect" parts. – Daniel Marques Apr 05 '17 at 20:59

1 Answers1

1

The Message property in ActionedEmailReport is not being instantiated. You need to add a constructor to your ActionedEmailReport and new up the Message property. You will probably need to do the same with the Body property in the Message class too.

christophano
  • 887
  • 2
  • 21
  • 27