Interfaces ic C#

  • Thread starter Thread starter Folke
  • Start date Start date
F

Folke

Allow me to ask a really stupid question.
Why use interfaces in C# and .NET if you're not dealing
with hereditary COM+ components / clients.
I can see no benefit from it. Only complicates things.
Doesn't add code security. You still must get hold of
the .dll for the interface implementing class. They talk
of it as a 'Contract' and say that the implementing class
must implement the specific code. But contracts can be
broken - what if the class implements other public
methods? Nothing prevents you from doing that.
 
Just an example!
-----------------------------------------------------------
using System;

namespace XmlWinApp.IBusiness
{
public interface IContract
{
void NiceMethod();
}
}
-----------------------------------------------------------
using System;
using System.IO;

namespace XmlWinApp.Business
{
public class IContractImplement
{
public IContractImplement()
{
}
public void NiceMethod()
{
// I'm a nice guy adhearing to the
contract.
}
public void NastyMethod()
{
// I'm not
FileStream fs = new FileStream
("IDontExist", FileMode.Open);
}
}
}
 
methods? Nothing prevents you from doing that.

But it guarantees that the members defined in the interface will be members
of any derived class.

This is how you can write a method that accepts an IDataReader parameter and
it will work with both an OleDbDataReader and an SqlDataReader (or any other
class that derives from IDataReader).

The contract only says that if the interface defines it, the derived class
must also include it. It does not say that if the interface does not include
then the derived class cannot include it.

Josh
 
Back
Top