0

I need a seperate class where I want to add to some Lists anytime I set a new value. Using _name.Add(value) within the set method doesn't work.

I tried the following

public class XMLInformation
{      
    public String BusType 
    {
        get
        {
            return SubBusType.LastOrDefault();
        }
        set
        {
            SubBusType.Add(value);
        }
    }
    public List<string> SubBusType { get; set; }

}

I use it like this:

        public STARC.GlobalVariables.XMLInformation XMLInformation = new STARC.GlobalVariables.XMLInformation();
        XMLInformation.BusType = "Test";

now i get an error message (sorry error is partly in geeman)

ISSUE

What am I doing wrong?

TheMan
  • 35
  • 5
  • what does the exception mean in English? if it is object reference not set to null exception, you have to first initialize the list – vivek nuna Jun 19 '20 at 12:09
  • 4
    `public List SubBusType { get; set; } = new List();` – bolkay Jun 19 '20 at 12:10
  • 2
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Martin Backasch Jun 19 '20 at 12:12

2 Answers2

2

It can solve your issue. List is not initialized and you are using it. so initialize it first and then use.

public class XMLInformation
{
    public String BusType
    {
        get
        {
            return SubBusType == null ? null: SubBusType.LastOrDefault();
        }
        set
        {
            if (SubBusType == null)
                SubBusType = new List<string>();
            SubBusType.Add(value);
        }
    }
    public List<string> SubBusType { get; set; }
}

Or

public class XMLInformation
{
    public String BusType
    {
        get
        {
            return SubBusType.LastOrDefault();
        }
        set
        {
            SubBusType.Add(value);
        }
    }
            public List<string> SubBusType { get; set; } = new List<string>();
}
vivek nuna
  • 12,695
  • 7
  • 48
  • 123
0

You have to Initialize the SubBusType object because at starting it will be null.

You can do either by creating in the constructor like below

 public XMLInformation()
        {
            SubBusType = new List<string>();
        }

or initiate on declaring the SubType itself like below.

public List<string> SubBusType { get; set; } = new List<string>();
surya teja
  • 20
  • 6