0

I want to serialize simple class as for example like below and write to XML file.

Sample Class file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleXMLSerializeDeserialize
{
    public class SampleXML
    {
        public SampleXML()
        {

        }
        public List<IndividualInfo> IndividualInfo { get; set; }
        public List<CommunicationInfo> Communication { get; set; }
    }

    public class IndividualInfo
    {
        public String Name { get; set; }
        public String Age { get; set; }
    }

    public class CommunicationInfo
    {
        public String presentAdd { get; set; }
        public String permanentAdd { get; set; }
    }
}

Serialization Method:

namespace SampleXMLSerializeDeserialize
{
    class Program
    {
        static void Main(string[] args)
        {
            SampleXML s = new SampleXML();
            s.IndividualInfo[0].Name="Jyoti";
            s.IndividualInfo[0].Age = "25";

            s.Communication[0].permanentAdd = "Dhaka";
            s.Communication[0].presentAdd = "Dhaka";
            XmlSerializer serializer = new XmlSerializer(typeof(SampleXML));
            StreamWriter str = new StreamWriter(Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + @"\SAM.XML");
            serializer.Serialize(str, s);
        }
    }
}

I am getting System.NullReferenceExeption at following line: s.IndividualInfo[0].Name="Jyoti";

Would you please help, what I am missing

jchoudhury
  • 359
  • 2
  • 8
  • 20
  • 1
    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 Apr 08 '14 at 04:46

2 Answers2

3

You never instantiate the [0] object of the collection and the collection itself. Use this:

s.IndividualInfo = new List<IndividualInfo>();
s.IndividualInfo.Add(new IndividualInfo { Name = "Jyoti" });
Artyom Neustroev
  • 8,224
  • 4
  • 29
  • 54
0

Have your constructor as

    public SampleXML()
    {
     IndividualInfo = new List<IndividualInfo>();
     Communication = new List<CommunicationInfo>();
    }

the list is not being initialized and is null. do the same for the other list as well.

And then use the Add method instead of indexed access.

s.IndividualInfo.Add(new IndividualInfo { Name = "Jyoti", Age = 25 });
Raja Nadar
  • 9,006
  • 2
  • 28
  • 39