3

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?

1
  • public double TotalAmount => product.Price * quantity; or in old syntax: public double TotalAmount { get { return product.Price * quantity; } } Commented Oct 4, 2017 at 16:42

2 Answers 2

5

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;
}   
Sign up to request clarification or add additional context in comments.

1 Comment

I think you mean product.Price
3

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;
            }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.