0

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.

Jazimov
  • 12,626
  • 9
  • 52
  • 59

2 Answers2

7

Use 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.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

Selman22's solution is correct. An alternative solution is to insert a cast:

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

However this is considered by some programmers to be somewhat inelegant. Either works and is commonly seen in production code.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • I used to think this was inelegant. However I employ it routinely now and find the code is very clean. If you aren't sure whether your object implements an interface then you have a genuine decision point in your program. – Brendan Hill Feb 26 '14 at 04:09
  • I like this approach too and I actually feel it's more 'elegant' than the accepted answer above. I was unfamiliar with the As keyword, however. – Jazimov Feb 26 '14 at 04:36
  • I just realized an advantage here is that you don't need to create a new variable. This might be appealing to some readers. – Jazimov Feb 26 '14 at 04:43
  • 1
    But if you use MS static code analyzer (e.g. FxCop), you'll get performance warning [CA1800: Do not cast unnecessarily](http://msdn.microsoft.com/en-us/library/ms182271.aspx), because your code performs duplicate cast to type 'IBuyer' and such casts slightly decrease performance. – Igor Kustov Feb 26 '14 at 05:18
  • 4
    @IgorKustov: Though there are few programs indeed whose amazing performance can be credited to their avoiding an unnecessary type check. – Eric Lippert Feb 26 '14 at 05:35
  • Jon Skeet weighed in on SO at [Casting vs using the 'as' keyword in the CLR](http://stackoverflow.com/a/496167/18192). – Brian Feb 26 '14 at 14:58