Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

i didnt understand why do i need interfaces.

they areant implementing anything. only the method names...

and if im not wrong i can use a specific interface only on a class where the method names are the same as in the interface. so a specifict interface fits only for a specific class.... :-\

why do i need it????????

Posted (edited)

One of the key things to understand about an interface is that it is a type.

It is abstract, yes, and the implementation is up to you, but you can create a variable from the interface.

 

I didn't really understand what their importance or power was until I saw an example like this:

 

Lets make an interface 'IGreet'.

interface IGreet
{
   void Greet();
}

Now here are two implementations of IGreet, one in English and another in Spanish:

class EnglishGreet : IGreet
{
   public void Greet()
   {
       Console.WriteLine("Hello");
   }
}

class SpanishGreet : IGreet
{
   public void Greet()
   {
       Console.WriteLine("Hola");
   }
}

 

You can declare an IGreet variable like this:

 

IGreet greeter = new SpanishGreet;

greeter.Greet() // Will output "Hola"

greeter = new EnglishGreet;

greeter.Greet() // Will output "Hello"

 

 

You can even create a factory-like class for it:

class GreetFactory
{
   public static IGreet Generate(string type)
   {
       switch(type)
       {
           case "English":
               return new EnglishGreet();
           case "Spanish":
               return new EnglishGreet();
           default:
               return null;
       }
   }
}

 

You can then use the factory class like so:

 

IGreet greeter = GreetFactory.Generate("English");

...

 

 

These examples don't really do much, but you can see an interface's power is in its abstraction. It is not an actual class, but it seems to behave like one.

Edited by BlackStone
"For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken
Posted
One of the key things to understand about an interface is that it is a type.

It is abstract, yes, and the implementation is up to you, but you can create a variable from the interface.

 

I didn't really understand what their importance or power was until I saw an example like this:

 

Lets make an interface 'IGreet'.

interface IGreet
{
   void Greet();
}

Now here are two implementations of IGreet, one in English and another in Spanish:

class EnglishGreet : IGreet
{
   public void Greet()
   {
       Console.WriteLine("Hello");
   }
}

class SpanishGreet : IGreet
{
   public void Greet()
   {
       Console.WriteLine("Hola");
   }
}

 

You can declare an IGreet variable like this:

 

IGreet greeter = new SpanishGreet;

greeter.Greet() // Will output "Hola"

greeter = new EnglishGreet;

greeter.Greet() // Will output "Hello"

 

 

You can even create a factory-like class for it:

class GreetFactory
{
   public static IGreet Generate(string type)
   {
       switch(type)
       {
           case "English":
               return new EnglishGreet();
           case "Spanish":
               return new EnglishGreet();
           default:
               return null;
       }
   }
}

 

You can then use the factory class like so:

 

IGreet greeter = GreetFactory.Generate("English");

...

 

 

These examples don't really do much, but you can see an interface's power is in its abstraction. It is not an actual class, but it seems to behave like one.

 

awesom examples! thanksss!!!!! many thanks ...!!!

this OOP makes a bit difficults for a new c#\c++ programmer....but its a basic key and i have to understand this.

Posted

before you write a class, you should always start with an interface.

 

define the way the looks (properties) acts (methods) and reacts (events) to the outside world, first. before you do any implementation.

 

As a matter of fact, you can do virtually, no pun intended, all your UI design, coding and debugging against the interfaces before you have the implementations defined.

 

I highly recommend Programming .NET Components, by far the best book I have read on leveraging the .NET framework.

Joe Mamma

Amendment 4: The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no warrants shall issue, but upon probable cause, supported by oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized.

Amendment 9: The enumeration in the Constitution, of certain rights, shall not be construed to deny or disparage others retained by the people.

Posted
I have a hard time (at times) keeping interace and abstract classes seperated, I keep with the HAS A and IS A concept, but sometimes they get mixed up as in this example.... a Ford IS A car (so Ford would derive from car), but a Human HAS A car (implies that car should be an interface)... Joe... how to you personally handle these kind of situations, I deal with them okay I guess; the fact that .NET only allows you to derive from one class makes it a lot easier to pick the best method...in this case I would use an interface (ICar), but Joe and Blackstone, how would you've of done this and why and what are your thoughts for picking whether to use an interface or an abstract class; the HAS A/IS A works in most situations, but I'm sure there are other school of thoughts too and I'm interested in hearing them.
  • Administrators
Posted

A good technique is to use both.

Inheritance is a good tool when you not only have similar functional requirements but also code reuse within the class hierarchy.

Interfaces on the other hand give no code reuse within the classes that implement them but do allow those classes to expose the same functions and be used interchangably in functions that expect the interface to be present.

 

If you create the initial interface you can then create an abstract class that implements this interface. Any class that then inherits from this interface will also implement the interface as well. This gives you the flexibility to use functionality in the base class where appropriate but also be able to implement the interface directly when required.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted

many thanks! im printing your replies...of all of you...they really help me!!!

and btw,the idea of implementing an interface in multipile classes is pressty weired,i guess,because the interface has to include all the classes methods that thats its implementing and then it makes him pretty big isnt it???

for e.g:

interface ICars

{

string Color(string c);

int void CarModel();

float Acceleration(string m);

}

 

The classes that inherits from it:

class Ford : ICars

{

string Color(string c);

{

.

.

}

int void CarModel();

{

.

.

.

}

 

float Acceleration(string m);

{

.

.

.

}

 

Lets say that there is another class that contains only one method from the ICars,so in this case i would be still able to use the interface on it?

Posted
With interfaces you have to implement each method, if you have a class that only implements part of things of that interface, then you have a couple of options, you can make the method you implement private, I believe. This will hide it from any callers and it's not like someone is forcing you to use the method in your own class. I think there is also a way of hiding it that is better suited. My point would be that if you have a class that doesn't implement all the members, and especially if you have several classes where this is the case possible you should re-write your interfaces. It's possible to have an interface inherit from another interface; I have trouble doing that though...so no example but it is possible. Basically what this means is you could have a very basic interface that WILL apply to all things, and then two or three derived interfaces that are more specific. But remember, if your getting too specific, where something is only being used by one or two things, maybe it shouldn't be an interface at all. There is a fine balance, and you should really look at the project as a whole, and ideally you want to keep interfaces that inherit from another interface to a minimum.
Posted (edited)

To make part of an interface hidden, declare the function explicitly. An example using the ICollection Interface:

 

public int Count
{
   ...
}
void ICollection.CopyTo(Array array, int index)
{
   ...
}
bool ICollection.IsSynchronized
{
   ...

object ICollection.SyncRoot
{
   ...
}

 

In the above code we implicitly implemented Count, but explicitly implemented CopyTo, IsSynchronized, SyncRoot. Implictly implemented methods must be declared public(else that would defeat the entire purpose of having an interface!!). Explicitly implemented methods cannot contain scope modifiers(public, private, etc.) and are not visible in the class that is implementing the interface, but when you use the class like this:

ICollection collection = new MyCollectionClass()

All the implemented methods are now visible.

 

IMHO, interfaces should be used when you need a blueprint that all you classes should adhere to. An abstract class should be used when you need a common functionality amongst all your derived classed, but don't want the class to be used in it of itself (I could give an example of this if wanted).

 

People feel that every class should always implement an interface. I am of the opinion that sometimes that is just overkill. Use you best judgment, but always make your code legible and easily maintainable.

Edited by BlackStone
"For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken
Posted (edited)

Thank you for the corrections. Hmmm... maybe I'm not understanding the diff between explicit and implicit implementation, I created the following test:

 

     public interface ITest
     {
         int Value { get;}
         void DoSomething();
     }
     public class Derived1 : ITest
     {
         #region ITest Members
 
         int ITest.Value
         {
             get
             {
                 this.DoSomething();        //okay, visible
                 return 0;
             }
         }
 
         public void DoSomething()
         {
             //int i = this.Value;        //not visible, compile error
         }
 
         #endregion
     }
     public class Derived2 : Derived1    
     {
         public Derived2()
         {
             base.DoSomething();            // visible
             //int i = base.Value;        //not visible, compile error
 
             //instance of Derived1
             Derived1 test = new Derived1();
             test.DoSomething();            //visible, okay
             //int i = test.Value;        //not visible, compile error
         }
     }
 

 

At no point can I get ITest.Value, whether in the class that implement the interface, a class that derives from the calss that implements the interface, or a new instance of that class. What am I doing wrong? It seems by explicitly implementing an interface you are ensuring that the property or function cannot be seen or even used from that point forward, so it would only seem to hide it. But based upon what you said my new instance of that class should see it, so maybe I'm using it wrong. The basics of inheritance and interface I have down, it's these more complicated versions of it that get me. Thanks for you input so far; it's been very educational.

Edited by bri189a
Posted

In order to access explicitly implemented interface members, you need to use the interface itself.

 

You would do that like this:

Derived1 derived = new Derived1();
ITest test = derived;
int testValue = test.Value;

 

This lets you hide any methods that you need to implement, but shouldn't be seen by anyone except for methods that use the interface(I use it for IEnumerable, I can't find a reason why I would want to access GetEnumerator() :) )

"For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken
  • 4 weeks later...
Posted
Okay then how to do you do implict implementations of interfaces? Basically I want to hide the implemented member from derived classes. Thanks PD! You've been a real help in my transition back to VB!

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...