Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to initialize a list with new in c#?

Tags:

c#

I have the following class:

public class CityDetailViewModel
{
    public IEnumerable<City.Grid> Detail { get; set; }
    public SelectList Statuses { get; set; }
    public string Topics { get; set; }
    public SelectList Types { get; set; }
}

In my code I have:

    public ActionResult getGrid(string pk, string rk) {
        var ms = new List<long>();
        var sw = Stopwatch.StartNew();
        var vm = new CityDetailViewModel();

I want to put the variable ms into my CityDetailViewModel class.

public class CityDetailViewModel
{
    public IEnumerable<City.Grid> Detail { get; set; }
    public SelectList Statuses { get; set; }
    public string Topics { get; set; }
    public SelectList Types { get; set; }
    public List<long> MS { get; set; }
}

Is this the correct way to do it. I'm not sure but do I need to use "new". Also in my code I add to the list using:

ms.Add(sw.ElapsedMilliseconds);

If it is part of the CityDetailViewModel can I still do that using:

MS.Add(sw.ElapsedMilliseconds);
like image 668
Angela Avatar asked Dec 20 '25 11:12

Angela


1 Answers

When you create a new instance of CityDetailViewModel, the member MS will be null, hence calling Add on it will raise a NullReferenceException.

You can either create a new List<long> inside the class' constructor, or create a new one outside of it

public class CityDetailViewModel
{
     ...

     public CityDetailViewModel()
     {
         this.MS = new List<long>();
     }
}

public ActionResult getGrid(string pk, string rk) {
    var sw = Stopwatch.StartNew();
    var vm = new CityDetailViewModel();
    ...
    vm.MS.Add(sw.ElapsedMilliseconds);

or

public ActionResult getGrid(string pk, string rk) {
    var ms = new List<long>();
    var sw = Stopwatch.StartNew();
    var vm = new CityDetailViewModel() { MS = ms };
    ...
    ms.Add(sw.ElapsedMilliseconds);

since ms and vm.MS will be the same list instance here.

like image 120
sloth Avatar answered Dec 23 '25 01:12

sloth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!