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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With