Your attachment types look like static data to me, so I'd personally make AttachmentType
an immutable class and define your common bits as static
members. I also like making things like this implement an interface
for ease of mocking during unit testing. So I have this:
public interface IAttachmentType
{
string MimeType
{
get;
}
string FriendlyName
{
get;
}
string Extension
{
get;
}
}
public sealed class AttachmentType : IAttachmentType
{
private static readonly IAttachmentType unknownMime =
new AttachmentType("application/octet-stream", "Unknown", string.Empty);
private static readonly IAttachmentType photo = new AttachmentType("image/png", "Photo", ".png");
private static readonly IAttachmentType video = new AttachmentType("video/mp4", "Video", ".mp4");
private static readonly IAttachmentType document = new AttachmentType("application/pdf", "Document", ".pdf");
private static readonly IAttachmentType unknown = new AttachmentType(string.Empty, "Unknown", string.Empty);
private readonly string mimeType;
private readonly string friendlyName;
private readonly string extension;
// Possibly make this private if you only use the static predefined MIME types.
public AttachmentType(string mimeType, string friendlyName, string extension)
{
this.mimeType = mimeType;
this.friendlyName = friendlyName;
this.extension = extension;
}
public static IAttachmentType UnknownMime
{
get
{
return unknownMime;
}
}
public static IAttachmentType Photo
{
get
{
return photo;
}
}
public static IAttachmentType Video
{
get
{
return video;
}
}
public static IAttachmentType Document
{
get
{
return document;
}
}
public static IAttachmentType Unknown
{
get
{
return unknown;
}
}
public string MimeType
{
get
{
return this.mimeType;
}
}
public string FriendlyName
{
get
{
return this.friendlyName;
}
}
public string Extension
{
get
{
return this.extension;
}
}
}
Then, to avoid a big long switch
, I put those into a Dictionary<T,U>
as such (note the case-insensitive specification, which will remove the ToUpper()
later). You can add MIME types with your detection string as needed:
private static readonly IDictionary<string, IAttachmentType> mimeMap =
new Dictionary<string, IAttachmentType>(StringComparer.OrdinalIgnoreCase)
{
{ "IVBOR", AttachmentType.Photo },
{ "/9J/4", AttachmentType.Photo },
{ "AAAAF", AttachmentType.Video },
{ "/9J/4", AttachmentType.Document },
};
Your calling code then simplifies to:
public static IAttachmentType GetMimeType(this string value)
{
if (string.IsNullOrEmpty(value))
{
return AttachmentType.UnknownMime;
}
IAttachmentType result;
return mimeMap.TryGetValue(value.Substring(0, 5), out result) ? result : AttachmentType.Unknown;
}