jeudi 12 avril 2018

Switch value to decide which subclass to use

I have an abstract class Payment, which is implemented by several PaymentTypes

    public abstract class Payment
    {
        protected int contract;
        public Payment(int contract)
        {
            this.contract = contract;
        }

        public abstract bool Aprove();
    }

and then, two classes which implement it

public class PaymentA : Payment
{
    public PaymentA(int contract) : base(contract)
    {
        this.contract = contract;
    }

    public override bool Aprove()
    {
        return true;
    }
}
public class PaymentB : Payment
{
    public PaymentB(int contract) : base(contract)
    {
        this.contract = contract;
    }

    public override bool Aprove()
    {
        return true;
    }
}

Now, I need to create PaymentA or PaymentB depending on a form field

static void Main(string[] Args)
{
    int contract = 1;
    Payment payment;
    switch (rbtPaymentType)
    {
        case (int)EPaymentTypes.A:
            payment = new PaymentA(contract);
            break;
        case (int)EPaymentTypes.B:
            payment = new PaymentB(contract);
            break;
    }

    payment.Aprove(); //Use of unassigned local variable
}

I have two questions:

1 - Is it well constructed so I can call payment.Aprove() no matter which type of payment it is?

2 - How can I do the method call if the object is not initialized? I get error "Use of unassigned local variable"

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire