Object reference of C # MVC class not set to object instance
Can anyone help me work around my problem with my class?
I have an Address class:
public class Address
{
public string addressDescription { get; set; }
public string addressNumber { get; set; }
public string adddressLine1 { get; set; }
public string adddressLine2 { get; set; }
public string adddressLine3 { get; set; }
public string addressPostCode { get; set; }
public double addressLatitude { get; set; }
public double addressLongitude { get; set; }
}
And I have a route class:
public class Route
{
public Address from { get; set; }
public Address to { get; set; }
}
And in my controller, I have set some dummy information like this:
public ActionResult FareCalculator(string from , string to)
{
var myroute = new Route();
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
}
but when i run the project it crashes at myroute.from.addressDescription = from; the line says the object reference is not set to an object instance.
I can't see what I am doing wrong. Can anyone please help?
thank
Trev
source to share
You need to create a new instance Address
and assign it from
and to
:
public ActionResult FareCalculator(string from , string to)
{
var myroute = new Route();
myroute.from = new Address(); // new instance
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to = new Address(); // new instance
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
}
source to share
May I suggest using a constructor to initialize the from and to fields? Otherwise, you will have to create new objects every time you use the Route class.
public class Route
{
public Address from { get; set; }
public Address to { get; set; }
public Route()
{
from = new Address();
to = new Address();
}
}
This way you can use your code as you pointed out:
var myroute = new Route();
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
source to share
myroute.from
and myroute.to
shoud is an instance of the class Address
.
public ActionResult FareCalculator(string from , string to)
{
var myroute = new Route();
myroute.from = new Address();
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to = new Address();
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
}
source to share