Possible Duplicate:
Ternary Expression with Interfaces as a Base Class
Classes:
interface ISms {
void f_SendSms();
}
class SmsVodafone : ISms {
public void f_SendSms(){
// ...
}
}
class SmsClickatell : ISms {
public void f_SendSms(){
// ...
}
}
This works:
ISms sms = null;
if (string.IsNullOrEmpty(_bilgi.M_Originator))
{
sms = new SmsVodafone();
}
else
{
sms = new SmsClickatell();
}
This works too:
ISms sms = null;
sms = string.IsNullOrEmpty(_bilgi.M_Originator)
? (ISms) new SmsVodafone()
: new SmsClickatell();
This doesn’t work:
ISms sms = null;
sms = string.IsNullOrEmpty(_bilgi.M_Originator)
? new SmsVodafone()
: new SmsClickatell();
Why?
In a ternary expression
a ? b : c, both expressionsbandcmust be convertible to the same type, which must be one ofb‘s type orc‘s type.SmsVodafoneis not convertible toSmsClickatell, andSmsClickatellis not convertible toSmsVodafone. That’s why you get an error.