Search code examples
c#enumerationinterface-design

How to replace enumeration with something like interface ID?


Please consider the following interfaces:

interface IFile
{
    // Members
};

interface IAudioFile : IFile
{
    // Members
};

interface IVideoFile : IFile
{
    // Members  
};

enum ContentType
{
    Audio,
    Video
};

interface IProvider
{
    HashSet<ContentType> GetSupportedTypes();
    IList<IFile> GetFiles(ContentType contentType);
};

I think that ContentType enumeration is redundant. Is there any way to use something like interface identifier instead of enumeration type?

Any comments on the interface design are very appreciated.


Solution

  • It really depends on what you're trying to accomplish, but I one options you may want to look at is using generics, so that IProvider is as so

    interface IProvider
    {
        IList<IFile> GetFiles<T>() where T: IFile;
    }
    

    which can be implemented like so

    public void ProviderConcrete()
    {
        public IList<IFile> GetFiles<T>()
        {
            if(typeof(t) == typeof(IAudioFile))
                .... get Audio files
    
        }
    }
    

    and called like so

    public void Caller()
    {
        var files = GetFiles<IAudioFile>();
    }