Friday 27 July 2012

A Guide to C# Interfaces for the Dotnet Architect

When drawing up an interface, one may wonder: "What are the valid constructs I can include in a C# interface?" An ARCHITECT of .Net software must be clear on this point, to be able to design interfaces that are a) SYNTACTICALLY CORRECT b) FIT FOR PURPOSE.

The answer is not as obvious as it may seem.

What CAN be put into a C# Interface? (MPE IND - Mumbai-Pune Expressway, India)
Methods, certainly.  Properties, yes. Events and indexers too - but not operators - why, because operators are declared static, and C# has no mechanism to require a type to implement static methods. The concept of interfaces in C# is thus much richer than the same construct in Java (which supports declaration of methods and constants).

What CANNOT be put into a C# Interface?
The reason why C# uses static operator overloading is based on cost/benefit analysis (read this piece from the C# compiler team. The question naturally arises since in  C++ operator overloading is done at instance level rather than static level (doesn't use the static keyword)). The upshot (or rather downshot) of this is that operator overloading cannot be prescribed at the interface level.

An Interface Specifies a Contract
A non-abstract implementation of an interface MUST implement ALL its members.

Accessibility Modifiers and Interfaces (Restaurant Example)
By definition, all interface members are public, since an interface is the public visage of a class or struct, it is what the class or struct wants to show to the outside world. (Like a restaurant that allows customers to orderFood, payBill, addTip and so forth). It may also have properties such as Address, StyleOfCuisine and so on. It may not expose the method CookFood unless clientele are able to cook their own food, for example using a grill built into the table. That may be part of the implementation but not part of the interface. An indexer may not be appropriate, unless be are creating an interface for RestuarantChain and want to access particular outlets of the chain. Events could be things like: CallForTakeawayOrder.

No comments: