1

I have a DTO as given below:

class Product
{
   public float cost{set;get;}
   public float sellprice{set;get}
}

And I have this ViewModel:

public class MyViewModel
{
   public Product products{set;get}
   public float profit{set;get}
}

The problem is that I need to calculate profit from Product properties but I don't know how to do it.

gurkan
  • 884
  • 4
  • 16
  • 25
mah
  • 95
  • 1
  • 10

1 Answers1

0

Use a property with an expression-getter, like so:

public class MyViewModel{
    public MyViewModel( Product product )
    {
        this.Product = product ?? throw new ArgumentNullException(nameof(product));
    }
    public Product Product { get; }
    public Decimal Profit => this.Product.SellPrice - this.Product.Cost;
}

Other feedback:

  • In C# and .NET:
    • Give types (class, struct, interface, etc) PascalCase names.
    • Give private fields, parameters and locals camelCase names.
    • Give public members (properties, methods) PascalCase names.
  • Do not use float or double to represent currency.
  • You should aim for using immutable types with read-only properties.
    • Mutable state makes it harder to reason about data-flow in your application.
Dai
  • 141,631
  • 28
  • 261
  • 374