Interface detection reflection

Total Post:183


 1324  View(s)
Rate this:

I have this code in my C# module:

if (customer is IBuyer) { customer.WaiveServiceFee(); }

This compiles fine, as long as customer is an object that implements IBuyer. But the whole idea of using the conditional is to test whether the customer object implemented IBuyer. If it hasn't, I get a compile-time error that customer does not contain a definition for WaiveServiceFee (WaiveServiceFee is method that results from IBuyer implementation--it, of course, is not part of the customer class).

I'm not familiar enough with C# to know how I can apply the logic above to call WaiveServiceFee at run-time and also make the program compilable?

Thank you.

  1. Re: Interface detection reflection

    Hi Ankita,

    Use as operator instead:

    var buyer = customer as IBuyer;

    if(buyer != null)


    If customer doesn't implement IBuyer, then buyer will be null.You can easily check whether the value is null or not and call your method if it's not null.After the assignment buyer will be considered as IBuyer in compile-time so you will be able to call your method without a compile-time error.


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.