Cpanel

# Articles

User Rating:  / 0
PoorBest

# C# and interfaces. Why are some declarations illegal?

## Introduction

While using IoC (Inversion of Control) and other modern design patterns, you manipulate quite often only interfaces and you do not want to care about the dirty quirks and details of the underlying implementations. I came to an interesting problem.

I have own abstracted values (IValue) that have an abstracted type (IType). The values are actually wrapped strings or wrapped integers (with a bunch of other special things of course otherwise I would have just used the base types!). Now I would like to let users of the framework I am defining write things like:

IValue value1 = ...;IValue value2 = ...;...IValue newValue = value1 + value2;

Of course this will not compile. But why actually restrict it to a compile-time check? Wouldn't it be a great feature?

## Restrictions on interfaces

You cannot define implicit conversions in interfaces.

You cannot overload operators in interfaces.

## Sketch of a solution

The underlying type of the value on the left side (newValue) plays a big role. The result of the operation shall be converted implicitly to that type. The operation at the interface level shall not be in one of the implementations of IValue but on a meta-level under the interface. Maybe it would make sense to introduce the concept of an interface handling code. The design restriction of that code is that it would have to know many things about the implementators of the interface. This could be performed at run-time with Reflexion or defining implicit specializations.

## Conclusion

Not sure about how to make the bridge to a good solution yet. But with the rising abstraction levels in today's complex software and its associated bunch of interfaces, there is in my opinion definitively a need for such a bridge to avoid cluttered and hardly readable code.