Using C#, is it possible to create a class that utilizes an object within its definition?

71 Views Asked by At

I am creating a Blazor WebAssembly app, and I have two classes (shown below). In WorkDay I want to calculate how much I will pay in taxes by using PayRate from the Job class. How can I get this to work?

public class WorkDay
{
    

    public double Hours { get; set; } 
    public double? Subtotal { get; set; }
    public double TaxRate { get; set; } = 0.1;
    public double Taxes
    {
        get { return ((Hours * 15.74) * TaxRate); } 
    }
    public double? Final 
    {
        get { return ((Hours * 15.74) - Taxes); }
    }

}

And

public class Job
{
    public Job(string organization, double payRate)
    {
        Organization = organization;
        PayRate = payRate;
    }
    public string Organization { get; set; }
    public double? PayRate { get; set; }
    public List<int> PayDays { get; set; } = new List<int>();
    public List<PayPeriod> PayPeriods { get; set; } = new List<PayPeriod>();
}
2

There are 2 best solutions below

1
Mike Bruno On

I think this is what you want:

class B {
    public int hourlyRate { get; set; }
}

class A {
    public B b { get; set; }
}
2
MrC aka Shaun Curtis On

The quick answer is WorkDay has a dependency on Job, so you need to add it as a property or field and set it in the constructor.

[Before someone jumps on me about SRP and other principles] There are other probably better ways of doing this, but without more context, it's impossible to comment constructively.

public class WorkDay
{
    public Job Job {get; private set;}
    public double Hours { get; set; } 
    public double? Subtotal { get; set; }
    public double TaxRate { get; set; } = 0.1;

    public double Taxes => ((Hours * this.Job.PayRate) * TaxRate); 
    public double? Final => (Hours * this.Job.PayRate) - Taxes);

    public WorkDay(Job job)
    {
       this.Job = job;
    }
}
public class Job
{
    public Job(string organization, double payRate)
    {
        this.Organization = organization;
        this.PayRate = payRate;
    }
    public string Organization { get; set; }
    // Set in Ctor so should not be nullable
    public double PayRate { get; set; }
    public List<int> PayDays { get; set; } = new List<int>();
    public List<PayPeriod> PayPeriods { get; set; } = new List<PayPeriod>();
}