Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET 4.5
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Amazon Web Services
Analysis Services
Android
Architecture
Arduino
ASP .NET Web API
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
BDD
Big Data
Bing
BizTalk
Book Excerpts
Build and Deploy
Business Intelligence
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE Framework Info - non Technical
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Debugger
Design Patterns
Development Process
Display Technologies
Distributed Computing
Document Database
DotNetNuke
DSL
Dynamic Languages
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
HTML 5
Internet Explorer 8.0
Interviews
IOS
iPhone
Iron Ruby
Java
Java Script
JavaScript
jQuery
JSON
Lightswitch
LINQ
Linux
LUA
Mac OS X
MDX
Messaging
Metro
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
MVVM
MySQL
Network
NHibernate
node.js
NOSQL
Nuget
Object Oriented Development
Objective C
Odata
OLAP
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
PHP
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Prolog
Python
Q&A
Rails
Rake
Razor
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Scheme
Search
Security
Services
SharePoint
SignalR
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server 2012
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
TFS
Tips
TypeScript
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 11
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio 2011
Visual Studio 2012
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WebMatrix
WF
Whitepapers
Windows 7
Windows 8
Windows Azure
Windows Live
Windows Phone 7
Windows Phone SDK
Windows Server
Windows Vista
WinForms
WinRT
Workflow
WPF
XAML
Xiine Documentation
XML
XNA
XSLT



LearnNow


XAMALOT
 


SSWUG

Reader rating:
Article source: CoDe (2002 - May/June)


Article Pages: < Previous - 1  2  3 4 5 - Next >


.NET Interface-based Programming (Cont.)

Defining and Using Interfaces

To implement an interface, all a class has to do is derive from that interface. Listing 1 shows the class MyClass implementing the interface IMyInterface.

"
By disallowing any kind of implementation detail in interfaces (such as method implementation, constants, static members, and constructors), .NET promotes loose coupling between the service providers. The client interface acts like a binary shield, isolating both parties from each other.
"

As trivial as Listing 1 is, it does demonstrate a number of important points. First, interfaces have visibility?an interface can be private to its assembly (using the internal visibility modifier) or it can be used from outside the assembly (the public visibility modifier), as in the listing. Second, even though the methods the interface defines have no visibility modifiers, they are by definition public and the implementing class has to declare its interface methods as public. Third, there is no need for using new or override to qualify the method redefinition in the subclass because an interface method by nature cannot have any implementation and, therefore, there is nothing to override. Fourth, the class must implement all the methods the interface defines, without exception. If the class is an abstract class, then it can redefine the methods without providing concrete implementation.

To interact with the object using the interface, all a client has to do is down cast the object to the interface, similar to using any other base type. Using the same definitions as in Listing 1, the client code might be:

IMyInterface obj;
obj = new MyClass();
obj.Method1();

Interfaces promote loose coupling between clients and objects. When using interfaces, there is a level of indirection between the client code and the object implementing the interface. If the client was not responsible for instantiating the object, then there is nothing in the client code pertaining to the object hidden behind the interface shield. Because of this, there could be many possible implementations of the same interface, such as:

public interface IMyInterface
{...}
public class MyClass : IMyInterface
{...}
public class MyOtherClass : IMyInterface
{...}

When a client obtains an interface reference by creating an object of type MyClass, the client is actually saying to .NET, "give me the interpretation of MyClass to the way IMyInterface should be implemented."

Interfaces and Error Handling

This sort of casting down from a class instance to an interface:

IMyInterface obj;
obj = new MyClass();
obj.Method1();

is called implicit cast because the compiler is required to figure out which type to down cast the class to. When using implicit cast, the compiler enforces type safety. If the class MyClass does not implement the IMyInterface interface, then the compiler refuses to generate the code and produces a compilation error. The compiler is able to do that because it can read the class's metadata and can tell in advance that the class does not derive from the interface. However, there are a number of cases where developers use an explicit cast instead of the implicit cast. The first is for readability. Sometimes you want to convey to readers explicitly what interface to expect to get back:

obj.Method1();
IMyInterface obj;
/* Some code here */
obj = (IMyInterface) new MyClass();
obj.Method1();

Explicit down cast to the interface is at the expense of type safety. Even if the class does not support the interface, the compiler still compiles the client's code and .NET throws an exception at runtime. The second case where explicit cast is used is with class factories. In object-oriented programming, clients often do not create objects directly, but rather get their instances from some class factory (see the Abstract Factory design pattern in Object Oriented Design Patterns, pp 87, ADW 1994). In that case, explicit down cast is unavoidable because the class factory returns some generic base type, which is usually object:

IClassFactory factory; 
/* Some code to initialize the class factory */
IMyInterface obj;
//GetObject() returns System.Object
obj = (IMyInterface)factory.GetObject(); 
obj.Method1();

The third case that mandates explicit down cast is when you have one interface the class implements, and you want to use it to get hold of another interface the class supports. Consider the code in Listing 2. Even when the client uses implicit cast to get hold of the first interface, it must do an explicit down cast to obtain the second.

In all of these examples of explicit down cast, you must incorporate error handling in case the type you are trying to down cast from does not support the interface. You can use try and catch statements to handle the exception, but you can also use the as operator to do a safe down cast. The as operator performs the cast if it is legal and assigns a value to the variable. However, if a down cast is not possible, the as operator assigns null to the interface variable, instead of throwing an exception. Listing 3 shows how to use the as operator to perform a safe cast that does not result in an exception in case of an error.

Interestingly, using the as operator to determine whether a particular object supports a given interface is semantically identical to COM's QueryInterface() method. Both mechanisms allow clients to defensively obtain an interface from an object and handle the situation when it does not support it.

&


Interface Naming

When you name a new interface type, prefix it with a capital "I," followed by a capital letter of the domain term, such as IAccount, ICalculator, etc. Use the "I" prefix even if the domain term itself starts with an "I" (such as IInternetManager). In spite of the fact that .NET tries to do away with the old Windows and C++ Hungarian naming notations (prefixing a variable name with its type), the "I" prefix is a direct legacy from COM, and that tradition is maintained in .NET.



Listing 1: Defining and implementing an interface
public interface IMyInterface
{
  void Method1();
  void Method2();
  void Method3();
}
 
public class MyClass : IMyInterface
{
  public void Method1(){...}  
  public void Method2(){...}  
  public void Method3(){...}
  //other class members 
}


Listing 2: : Defining and using multiple interfaces
public interface IMyInterface
{
  void Method1(); 
  void Method2(); 
}
public interface IMyOtherInterface
{
  void Method3(); 
}
 
public class MyClass : IMyInterface,IMyOtherInterface
{
  public void Method1(){...}  
  public void Method2(){...}  
  public void Method3(){...}  

//Client side code:
IMyInterface obj1;
IMyOtherInterface obj2;

obj1 = new MyClass();
obj1.Method1();

obj2 = (IMyOtherInterface)obj1;
obj2.Method3();


Listing 3: Using the as operator to down cast safely to the desired interface.
SomeType obj1;
IMyInterface obj2;

/* Some code to initialize obj1 */

obj2 = obj1 as IMyInterface;
if(obj2 != null)
{
   obj.Method1();
}
else
{
   //Handle error in expected interface 
}


Article Pages: < Previous - 1  2  3 4 5 - Next Page: 'Separation of Interface from Implementation' >>

Page 1: .NET Interface-based Programming
Page 2: Defining and Using Interfaces
Page 3: Separation of Interface from Implementation
Page 4: Interface Methods Collusion
Page 5: Interface Factoring and Design

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
4.6 out of 5

5 people have rated this article.

Instantly Search Terabytes Of Text
“Lightning Fast”
– Redmond Mag
“Covers all data
sources” – eWeek
25+ fielded & full-text search options
dtSearch’s own document filters highlight hits in popular file types
Web Spider supports static & dynamic data
APIs for .NET, Java, C++, SQL, etc.
Win / Linux (64-bit & 32-bit)
www.dtSearch.com
 

      LearnNow

 

SSWUG