griegs
griegs

Reputation: 22760

Calling method defined in Base Interface

If I have the following Interface structure;

public interface IPaymentTypeBase
{
    void PayNow();
    double Amount { get; set; }
}

public interface IPaymentTypePayPal : IPaymentTypeBase
{
    string UserName { get; set; }
    string Password { get; set; }
}

public interface IPaymentMethod<T>
{
}

Then I have the following classes;

public class PaymentTypePayPal : IPaymentTypePayPal
{
    public string UserName { get; set; }
    public string Password { get; set; }

    public void PayNow()
    {
        throw new NotImplementedException();
    }
}

public class PaymentMethod<T> : IPaymentMethod<T> where T : IPaymentTypeBase
{
}

Then in my web application I have this;

IPaymentMethod<IPaymentTypePayPal> payer = (IPaymentMethod<IPaymentTypePayPal>) new PaymentMethod<PaymentTypePayPal>();

I'd now like to call payer.PayNow(); but I'm just getting lost in interfaces etc and can't seem to make this work.

I believe this is a simple thing but am just missing the point entierly.

Can anyone help?

Edit

The intention here is to have a set of interface such as PayPal, Voucher, CreditCard all of which do their own payment gateway type of stuff.

So I'd like to instantiate a class that takes the Payment Type as an interface and call that interfaces PayNow method.

Upvotes: 0

Views: 248

Answers (3)

Rob Ferrante
Rob Ferrante

Reputation: 31

Personally, I'd use classes rather than interfaces whenever inheritance is involved. Also, in this case you've got more indirection than you probably need. If you model Payment as an abstract base class (with PayNow() and Amount) and PayPalPayment as the subclass, just instantiate the proper subclass from a factory and you're set, with all the flexibility you'd have with your approach, yet easier to understand and maintain, I think. (not really knowing all of the other requirements of your application)

Upvotes: 0

Archana
Archana

Reputation: 99

I am not quite sure of why you are using that PaymentMethod class... But why cant you modify the interface IPaymentMethod to something like :

public interface IPaymentMethod<T> : IPaymentTypeBase

so that U can call the patNow method??

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93030

payer is of type IPaymentMethod<IPaymentTypePayPal>.

But IPaymentMethod<T> is defined as

public interface IPaymentMethod<T>
{
}

Therefore, it has no methods and you can't call PayNow() on it.

The same is true for PaymentMethod<T>, so you can't call any method on an instance of PaymentMethod<PaymentTypePaypal> either.

Maybe you can explain a little more what your intention is.

Upvotes: 1

Related Questions