Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Dictionary<string, class> to IDictionary<string, interface>

Tags:

c#

.net

I have a class that holds a dictionary of parameters:

public class Parameter : IExecutionParameter, IDesignerParameter
{
}

public interface IExecutionSettings
{
  IDictionary<string, IExecutionParameter> Parameters { get; }
}

public interface IDesignerSettings
{
  IDictionary<string, IDesignerParameter> Parameters { get; }
}

public class Settings : IExecutionSettings, IDesignerSettings
{
  private Dictionary<string, Parameter> _parameters;

  // TODO: Implement IExecutionSettings.Parameters
  // TODO: Implement IDesignerSettings.Parameters
}

I want to create explicit implementations of these interfaces (this I know how to do), but I can't figure out how to properly cast the dictionary.

Any help will be appreciated.

like image 523
Marcin Seredynski Avatar asked Sep 11 '25 09:09

Marcin Seredynski


1 Answers

You can't, because it wouldn't be safe. Suppose you could cast Dictionary<string, MemoryStream> to IDictionary<string, IDisposable> - you'd then be able to put any IDisposable value in the dictionary via the latter reference, even though the actual dictionary can only hold MemoryStream-compatible references.

You could potentially create a readonly dictionary wrapper which delegates to an underlying dictionary for all reads, and fails on all writes. You could then wrap your Dictionary<string, Parameter> in two of these "view" dictionaries. It would be a bit of a pain, but doable. Whether or not that's the most appropriate approach in your case is a different matter.

Perhaps instead you should have:

public interface IExecutionSettings
{
    IExecutionParameter this[string key] { get; }
}

public interface IDesignerSettings
{
    IDesignerParameter this[string key] { get; }
}

You could easily implement both of those (explicitly) within Settings.

like image 88
Jon Skeet Avatar answered Sep 14 '25 01:09

Jon Skeet