Recently I started making more use of interfaces and inheritance, and I try to pass those as parameters into functions to make my code more flexible.
But what really annoys me when I use generic functions is that I always have to use the keywords is
and as
together.
For example:
interface Imail
{
string GetBody();
string GetSubject();
}
interface IAttachment
{
IEnumerable<Attachment> GetAttachments();
}
public MailMessage GetMail<T>(T mailObject) where T: Imail
{
MailMessage mail = new MailMessage();
mail.Subject = mailObject.GetSubject();
mail.Body = mailObject.GetBody();
if (mailObject is IAttachment)
foreach (var att in (mailObject as IAttachment).GetAttachments())
mail.Attachments.Add(att);
return mail;
}
This certainly doesn't make the code more readable, and is just not needed in my opinion. Why can't I just use mailObject.GetAttachments()
after I check if it implements the interface (or baseclass for that matter) with is
? Or is it possible and am I just missing something? Please enlighten me with your wisdom SO senpais!
Why can't I just use mailObject.GetAttachments() after I check if it implements the interface (or baseclass for that matter) with is?
Because the compile-time type of the mailObject
variable is still just T
.
Note that currently you're performing the dynamic type check twice - a generally preferred approach is:
var attachment = mailObject as IAttachment;
if (attachment != null)
{
foreach (var att in attachment.GetAttachments())
{
mail.Attachmenets.Add(att);
}
}
The downside of that is that we've now got an extra variable in scope, of course.
C# 7 is likely to address this problem with new features around pattern matching, so with the current proposal you'd be able to write:
if (mailObject is Attachment attachment)
{
// Use attachment
}
(As an aside, I'd strongly recommend using braces even for single-statement if
and foreach
bodies. It makes it easier to read IMO, without having to rely on indentation always being perfect. I've seen far too many SO questions where coders have trusted the indentation and not noticed that their multiple statements aren't really related...)
See more on this question at Stackoverflow