Reputation: 11
I have a class Car, which has a property Owner. Owner has two properties: FirstName and LastName
In my unit testing shown below, I can't get access to the two name fields,
"The name "owner" does not exist in the current context"
namespace CodeExcercise
{
[TestClass]
public class TestClass
{
[TestMethod]
public void Test()
{
var cars = new List<Car>()
{
new Car() { owner.Firstname = "Brian", Lastname = "Badonde", Cost = 5, Registered = DateTime.Now},
};
new PrintMethod().PrintReport(cars, "CR.csv");
var outPut = File.ReadAllLines("CR.csv");
Assert.AreEqual(1, outPut.Count());
}
}
public class Owner
{
public string Firstname;
public string Lastname;
}
public class Car
{
public Owner owner;
public double Cost;
public DateTime Registered;
}
Upvotes: 0
Views: 49
Reputation: 54628
I have a class Car, which has a property Owner. Owner has two properties: FirstName and LastName
I think what you mean to say is
I have a car class, and I want to assign the Owner as an inline initializer.
in which case you have to create the type of the property and use the same inline initializer to set it's properties:
new Car
{
Cost = 5,
Registered = DateTime.Now,
Owner = new Owner
{
Firstname = "Brian",
Lastname = "Badonde"
},
}
I've used an upper case property name because Microsoft Guidelines recommend all properties start with an upper case character.
Upvotes: 3
Reputation: 218827
The syntax you're using to set the owner
properties here is incorrect:
new Car() { owner.Firstname = "Brian", Lastname = "Badonde", Cost = 5, Registered = DateTime.Now}
You'd create the Owner
object with the same syntax as creating the Car
object. For example:
new Car()
{
owner = new Owner()
{
Firstname = "Brian",
Lastname = "Badonde"
},
Cost = 5,
Registered = DateTime.Now
}
You can nest this as much as you like, each individual object creation is its own operation.
Upvotes: 5
Reputation: 19496
You have to create the new Owner
object:
new Car
{
owner = new Owner { Firstname = "Brian", Lastname = "Badonde" },
Cost = 5,
Registered = DateTime.Now
};
Upvotes: 3