Reputation: 3515
Hi I'm having trouble learning c# because in Java I was used to do this in Java
public class Product
{
private double price;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class Item
{
private int quantity;
private Product product;
public double totalAmount()
{
return product.getPrice() * quantity;
}
}
The totalAmount() method is an example with Java of how I use to access an value of an object in another class. How can I achieve the same thing in c#, this is my code
public class Product
{
private double price;
public double Price { get => price; set => price = value; }
}
public class Item
{
private int quantity;
private Product product;
public double totalAmount()
{
//How to use a get here
}
}
I don't know if my question is clear but basically what I want to know is how can I achieve a get or a set if my object is an actual value of one class?
Upvotes: 3
Views: 24694
Reputation: 670
In C# you have Properties: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties
And Auto-Implemented properties: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
You can achieve it using both:
public class Product
{
public decimal Price { get; set; }
}
public class Item
{
public Product Product { get; set; }
public int Quantity { get; set; }
public decimal TotalAmount
{
get
{
// Maybe you want validate that the product is not null here.
// note that "Product" here refers to the property, not the class
return Product.Price * Quantity;
}
}
}
Upvotes: 3
Reputation: 64943
First of all, don't use expression-bodied properties for this... Just use auto-properties:
public class Product
{
public double Price { get; set; }
}
Finally, you don't access the getter explicitly, you just get the value of Price
:
public double totalAmount()
{
// Properties are syntactic sugar.
// Actually there's a product.get_Price and
// product.set_Price behind the scenes ;)
var price = product.Price;
}
Upvotes: 5