10

I have a set of classes, each of which can open different types of files using an external application and tell that application to print the file to a particular printer. The classes all inherit a common abstract class and an interface.

internal interface IApplicationPrinter : IDisposable
{
    string ApplicationExe { get; }
    string ApplicationName { get; }
    string[] PrintableExtensions { get; }

    IApplicationPrinter CreateInstance(string Filename, string Printer);
    void Print();
    bool ExitApplicationAfterPrint { get; set; }
    bool WaitApplicationExitOnPrint { get; set; }
    System.IO.FileInfo PdfFile { get; protected set; }
}
internal abstract class ApplicationPrinter : IApplicationPrinter
{
    ...
}
internal class WordPrinter : ApplicationPrinter
{
    internal static string[] PrintableExtensions { get { return new string[]{".doc", ".docx" }; } }
    ...
}
internal class ExcelPrinter : ApplicationPrinter
{
    internal static string[] PrintableExtensions { get { return new string[]{".xls", ".xlsx" }; } }
    ...
}

I am trying to create a Dictionary of printable file extensions and corresponding Types of classes that can print such files. I do not want to instantiate the classes in the dictionary.

private static Dictionary<string, Type> FileConverters;
static Printer()
{
    FileConverters = new Dictionary<string, Type>();

    foreach (string ext in WordPrinter.PrintableExtensions)
    {
        FileConverters.Add(ext, typeof(WordPrinter));
    }

    string filename = "textfile.txt";
    string extension = filename.Substring(filename.LastIndexOf("."));

    if (FileConverters.ContainsKey(extension))
    {
        IApplicationPrinter printer = ((IApplicationPrinter)FileConverters[extension]).CreateInstance(filename, "Printer");
        printer.Print();
    }
}

Is there any way to make Dictionary<string, Type> FileConverters more type-safe, by restricting it to values that implement IApplicationPrinter? In other words, is something like this possible:

private static Dictionary<string, T> FileConverters where T: IApplicationPrinter;

Update: I do not want to store instances for the following two reasons:

  1. Each class can handle several different file types (see string[] PrintableExtensions). The dictionary stores extensions as keys. There is no utility in creating and storing multiple separates instance of the same class.
  2. Each printer class uses COM API and Office Interop to create instances of third-party applications. It's better that a new instance of each class is created for a print job when so required, and that the garbage collector can clean up afterwards.
1
  • Why don't you want to store instances in the dictionary?
    – svick
    Jan 28, 2012 at 11:13

4 Answers 4

7

I would do it slightly differently:

private Dictionary<String, Func<IApplicationPrinter>> _converters;

public void Initialise()
{
    foreach (string ext in WordPrinter.PrintableExtensions)
    {
        _converters.Add(ext, () => new WordPrinter());
    }
}

public IApplicationPrinter GetPrinterFor(String extension)
{
    if (_converters.ContainsKey(extension))   //case sensitive!
    {
        return _converters[extension].Invoke();
    }

    throw new PrinterNotFoundException(extension);
}

This method will not store instances in the dictionary as you require, and will create you a new instance each time you call GetPrinterFor. It also is more strongly typed as the return type of the Func<> has to be an IApplicationPrinter.

1
  • I've been looking for this solution! Thanks Pondidum, no need anymore for a huge if () new A(); else if () new B(); else if () new C(); else if () new... in my code.
    – Cœur
    Aug 14, 2014 at 10:34
3

Not directly - remember that the things you're putting in your dictionary are Type objects, not objects that implement IApplicationPrinter.

Probably the best option here is to check that each type you add to your dictionary implements IApplicationPrinter, by checking whether type.GetInterface("IApplicationPrinter") returns null or not.

3
  • I think it's best to avoid strings instead of types where possible. And it's possible here.
    – svick
    Jan 28, 2012 at 11:58
  • You're right - typeof(IApplicationPrinter).Name would be better than "IApplicationPrinter". Jan 29, 2012 at 14:11
  • I meant something more along the lines of typeof(IApplicationPrinter).IsAssignableFrom(type). Completely safe and no strings used whatsoever.
    – svick
    Jan 29, 2012 at 14:27
1

If you used Dictionary<string, IApplicationPrinter>, that doesn't necessary mean you will have to have different instance for each string, several of them can share the same instance.

If you don't want to do that, you can store factories in the dictionary. The factory can be an object that implements an interface (something like IApplicationPrinterFactory), or just a delegate that can create the object. In your case, that would be Dictionary<string, Func<IApplicationPrinter>>. Doing it this way is completely type-safe. To add to the dictionary, you would do something like:

FileConverters = new Dictionary<string, Func<IApplicationPrinter>>();

Func<IApplicationPrinter> printerFactory = () => new WordPrinter();

foreach (string ext in WordPrinter.PrintableExtensions)
    FileConverters.Add(ext, printerFactory);

If you're sure you want Dictionary<string, Type>, there is no way to limit that, so that all types in there implement IApplicationPrinter. What you could do is to create your own dictionary, that checks the type upon addition. This doesn't make compile-time safe, but it makes it more runtime-time safe.

class TypeDictionary : IDictionary<string, Type>
{
    private readonly Type m_typeToLimit;
    readonly IDictionary<string, Type> m_dictionary =
        new Dictionary<string, Type>();

    public TypeDictionary(Type typeToLimit)
    {
        m_typeToLimit = typeToLimit;
    }

    public void Add(string key, Type value)
    {
        if (!m_typeToLimit.IsAssignableFrom(value))
            throw new InvalidOperationException();

        m_dictionary.Add(key, value);
    }

    public int Count
    {
        get { return m_dictionary.Count; }
    }

    public void Clear()
    {
        m_dictionary.Clear();
    }

    // the rest of members of IDictionary
}
0

First you need to change your approach to access the extensions array because you can't access your property without creating a instance. I would use a custom attribute to tell your type-dictionary which extension each class supports. This will look like this:

[PrinterExtensions("txt", "doc")]
public class WordPrinter 
{
    .... // Code goes here
}

Using the attribute allows you to restrict the type. There are two ways to archive this.

  • Throw a exception in the constructor of the type ( see this link )
  • Use a abstract class instead of a interface, this allows you restrict you class by using a protected attribute ( at this point you need to create a base class for the attribute to access it from your type-dictionary ) which can only be applied to devired classes.

Now you can just can just check if a particular class has the PrinterExtensions attribute and access a property of it which retrieves all the extensions or call a method which directly registers all extensions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.