jean182
jean182

Reputation: 3515

Access to an object field or property from another class c#

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

Answers (2)

Bruno Avelar
Bruno Avelar

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

Matías Fidemraizer
Matías Fidemraizer

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

Related Questions