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.
Pravesh Singh
26-Mar-2014Use as operator instead:
var buyer = customer as IBuyer;
if(buyer != null)
buyer.WaiveServiceFee();
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.