Is it possible to define how to cast a built in object to an interface in C#? Interfaces can’t define operators. I have a very simple interface that allow index access, but not mutation:
public interface ILookup<K, V>
{
V this[K key] { get; }
}
I’d like to be able to cast a Dictionary<K, V> to an ILookup<K, V>. In my ideal dream world this would look like:
//INVALID C#
public interface ILookup<K, V>
{
static implicit operator ILookup<K, V>(Dictionary<K, V> dict)
{
//Mystery voodoo like code. Basically asserting "this is how dict
//implements ILookup
}
V this[K key] { get; }
}
What I’ve worked out as a workaround is this:
public class LookupWrapper<K, V> : ILookup<K, V>
{
private LookupWrapper() { }
public static implicit operator LookupWrapper<K, V>(Dictionary<K, V> dict)
{
return new LookupWrapper<K, V> { dict = dict };
}
private IDictionary<K, V> dict;
public V this[K key] { get { return dict[key]; } }
}
This works and means I can now directly cast from Dictionary to ILookup, but boy does it feel convoluted…
Is there a better way to force a conversion to an interface?
Thanks to @MBabcock’s comment I realized I was thinking about this wrong. I promoted the interface to a full on class as follows:
Any further conversions I need like this I can simply add an implicit operator