What does it really mean? I am reading design pattern book. It says
objects are accessed solely through their interfaces, and I am not able to get my head around it, can some body give me an example (Will really appreciate if its in C#)
What do we really achieve by using it?
Thanks
If you have a class called Espson and it implements an interface called IPrinter then you can instantiate the object by it's interface.
IPrinter printer = new Espson();
Epson may have a number of methods that are not part of the IPrinter interface but you may not care. All you may want to do is call a method defined in the IPrinter interface called Print
So then I can pass the class to a method called PrintDocument(IPrinter printer) and the method doesn't care what type of printer it is, it just knows it has a method called Print
The problem is the interface has several meanings. In this case the author is talking that objects must be accessed through public methods (in C# through public properties also) only.
(Of course, inheritors may use protected methods).
Public methods/properties form the public interface of a class. It's not the same interface that described by interface keyword in C#.
That really depends. If the variable is of type "interface", then in that case the object can be accessed by the interface type only.
Let's consider an example - Suppose I have an interface as defined below -
interface IMyInterface
{
string B();
}
and if I implement this interface using a class "MyClass" as shown below -
public class MyClass:IMyInterface
{
public string B()
{
return "In Class";
}
}
public class MyAnotherClass:IMyInterface
{
public string B()
{
return "In Another Class";
}
}
and I create an instance of the class using the interface as shown below
IMyInterface myinst = new MyClass();
then in the above case I can only get access to the Method B() using variable myinst which contains a reference to MyClass type.
Going further, let's say I have a method that takes a parameter of type IMyInterface as shown below -
public class UseOfInterface{
public void InterfaceUse(IMyInterface myPara)
{
myPara.B();
}
}
and I call this method as shown below -
IMyInterface myInst = new MyClass();
IMyInterface myAnotherInst = new MyAnotherClass();
UseOfInterface interfaceUse = new UseOfInterface();
interfaceUse.InterfaceUse(myInst); // returns "In Class"
interfaceUse.InterfaceUse(myAnotherInst); // returns "In Another Class"
Then, as shown above, it is decided at runtime as to which method is called using the Interface variable.
But if I had created a variable of type MyClass which would have contained a reference of type MyClass itself as shown below -
MyClass myinst = new MyClass();
then method B() can be accessed using the MyClass instance. So it depends what type of scenario you are dealing with.
Edit: Why Use Interfaces?
The main reason to use an interface is that it provides a contract to the class for which it is being implemented apart from the multiple inheritance support in C#. Let's can see an example where the contract providing can be helpful.
Suppose you have a class - "Car" in your assembly that you want to expose publicly, the definition of the class is as shown below
namespace CarNameSpace
{
public class Car()
{
public void Drive(IDriver driver)
{
if(driver.Age > 18)
{
driver.Drive();
}
}
}
}
As shown above, anyone who implements the IDriver interface can drive the car, which is defined below,
interface IDriver
{
string Age{get; set;}
string Name {get set;}
string Drive()
}
In turn to drive my car I would be exposing the IDriver interface to the outer world, so anyone who implements my interface can call the Car's Drive method, doesn't matter how he drives the car as shown below
public class PerfectDriver:IDriver
{
public PerfectDriver()
{
Name = "Vikram";
Age = 30;
}
public int Age{get; set;}
public string Name {get; set;}
public string Drive()
{
return "Drive's perfectly";
}
}
The Car class can be used as shown below
PerfectDriver perf = new PerfectDriver
Car myCar = Car();
myCar.Driver(perf);
An interface is a construct that describes the signature of the public members of an object. It contains declarations (declarations only, no implementation) of properties, methods and events that are guaranteed to be present on any object that implements that interface.
Here's a simple interface and a few classes that implement it. The interface "INamed" states simply that objects implementing the interface have a "Name" property that is a string.
public interface INamed{
string Name{get;}
}
public class Person : INamed{
public string Name{get;set;}
}
public class Place : INamed{
public string Name{get;set;}
}
public class Thing : INamed{
public string Name{get;set;}
}
...And a simple method that accepts a parameter of that interface type.
static void PrintName(INamed namedObject){
Console.WriteLine(namedObject.Name);
}
This "PrintName" method can accept a parameter of any type that implements that interface. The advantage of "accessing objects by their interface" is that it infuses your application with a certain flexibility, accessing these interfaces as opposed to their concrete types allows you to operate on these objects without having to know what they really are.
I could, for instance choose to operate on the IDbCommand interface as opposed to a concrete SqlCommand and much of what I write in this manner will be useful when working with a variety of database providers.
The simple idea is that you don't need to know if you're in a car or a boat because you can drive anything with a wheel and pedals.
The interface refers to what the object exposes to users of the object. An object will be an instance of a class which will have its own interface and possibly implement one or more other interfaces.
While languages such as C# allow you to define things called interfaces, those are distinct from the interface referred to in the statement that objects are accessed through their interfaces. In a language such as Scala, for instance, what C# calls an interface is called a trait. Most design patterns do involve the use of defined interfaces, i.e. public interface <interface name>, but again, those are distinct from what is meant in the original statement.
Suppose I define the following class in C#:
public class MyType
{
public void Method1()
{
...
}
private void Method2()
{
...
}
public int Method3()
{
...
}
}
Then the interface through which I interact with the class is the two methods it exposes, void Method1 and int Method2 and the implicit parameterless constructor.
Now, suppose I define the following interfaces and class:
public interface IInterface1
{
void Method1();
}
public interface IInterface2
{
int Method3();
}
public class MyType2 : IInterface1, IInterface2
{
public void Method1()
{
...
}
private void ADifferentMethod()
{
...
}
public int Method3()
{
...
}
}
The interface through which a user interacts with instances of MyType2 is the same as that through which a user interacts with instances of MyType1 (except for the different constructors) because the signatures of the public methods (and other public members) are identical : void Method1 and int Method3.
Related
I am having a abstract class which is being inherited by 2 classes. How can I find out which class is being created in my helper class.
Abstract Class
public abstract class AbstractClass
{
private IHelper helper{ get; }
public Entity()
{
helper= new MyHelper(this);
}
}
MyHelper.cs
public class MyHelper: IHelper
{
private AbstractClass ABClass{get;}
public EntityDataOperation(AbstractClass abClass)
{
//How can I find out which concrete type it is i.e. ClassA or ClassB
ABClass= abClass;
}
}
ClassA
public class ClassA:AbstractClass
{
public string data= "ClassA";
}
ClassB
public class ClassB:AbstractClass
{
public string data= "ClassB";
}
You can use Reflection but your code and methodology is very questionable:
entity.GetType().Name;
You can also test for the subclasses
if (abClass is ClassA)
// found is ClassA
else if (abClass is ClassB)
// found ClassB
It seems like your question boils down to, "If I have an object, how do I get the type of that object?"
var typeOfTheObject = theObject.GetType();
The problem is that this largely defeats the purpose of strongly typed parameters.
This tells you what you need to know about the type:
public EntityDataOperation(AbstractClass abClass)
^^^
That tells you what the type is. It's AbstractClass. If that's not what you need to know - if you don't care that it's an AbstractClass, then why not change the parameter to object?
Polymorphism literally means "multiple shapes." It means that the when you get an instance of AbstractClass, the actual object could be one of many shapes - many implementations of the class. But by taking a parameter of type AbstractClass, this method says that it doesn't care which type it is. It just interacts with the interface it knows about - the methods and properties of AbstractClass, without knowing or caring what the concrete implementation is.
I want to subclass a large number of classes so that they will all contain a certain set of the same properties. What would be the right way to do it in order to avoid repetition? I thought of using generics like:
public class SuperT<T> : T
{
//the same set of properties
}
But the compiler says
Cannot derive from 'T' because it is a type parameter
EDIT: I am trying to subclass some classes in a third party assembly so I cannot use a base class.
For example, the types are "Image", "Label", "Button" etc and I want to subclass them all to contain a property like "Radius". (So that I would use SuperImage element in XAML and when I set it's Radius property from XAML, I will be able to run some certain logic.)
One other way I just thought of right now is using T4 templates. I wonder if there is a way to do this with generics without resorting to templates? I cannot understand why the compiler rejects it.
If these classes all share a common base class or common interface you could write an extension method.
public static class ShapeExetnsionsExtLib
{
public static double Radius(this ShapeBase shape){
return /*calculate radious*/;
}
}
From comments
I am trying to subclass some classes in a third party assembly so I cannot use a base class.
For example, the the types are "Image", "Label", "Button" etc and I want to subclass them all to contain a property like "radius".
Yes they share common base classes but I cannot add anything new to them.
I don't think generics have anything to do with this, however inheritance is probably what you're looking for.
There are two types of inheritance that you can use to subclass, and extension methods work to "superclass"... sort of.
Is-A inheritance
Has-A inheritance
And to simply add a similar method to a bunch of third party objects, you'll use an extension method.
Is-A inheritance
Use a base class if you've got similar method implementations.
public abstract class BaseFoo {
public void Bar() {
// actual code
}
}
public class Foo : BaseFoo
{
}
var foo = new Foo();
foo.Bar();
Use an Interface if you need to implement the same method on each class.
public interface IFoo {
void Bar();
}
public class Foo : IFoo {
public override void Bar(){
// bar implementation
}
}
var foo = new Foo();
foo.Bar();
Combining the two is also allowed, but you can only inherit on base class, where you can inherit multiple interfaces.
Has-A inheritance
This is particularly useful with dependency injection, but it's simply the notion that you have an instance of another class to work with. It's essentially a wrapper class for you to work with.
public class Foo {
private readonly ThirdPartyFoo _tpFoo;
void Foo(ThirdPartyFoo tpFoo) {
_tpFoo = tpFoo;
}
public void Bar(){
// now I can do something with _tpFoo;
_tpFoo.Bar();
}
}
var tpFoo = new ThirdPartyFoo();
var foo = new Foo(tpFoo);
foo.Bar(); // invokes the underlying tpFoo
Lastly, if you just need to add a method to existing classes, then you create an extension method.
public static class ViewExtensions()
{
// this assumes your Image, Button, Label all inherit from View.
public static Whatever Radius(this View view) {
// do your radius work.
}
}
Just Use a base class:
public class Base
{
public int Id { get; set; }
public string Name { get; set; }
}
And inherite from it:
public class A : Base
{
}
public class B : Base
{
}
In general, you want to use one of the answers already posted about using a base class and inheriting from that. However, if the classes are in a third party library and are marked as sealed, then you will need to create a wrapper class to use as a base class.
(Note that this option is a workaround and doesn't truly inherit from the third party class, so things in that class that are marked as protected won't be accessible without a liberal use of reflection.)
// The sealed class within another library
public sealed ThirdPartyClass
{
public ThirdPartyClass(int i) { }
public int SomeProperty { get; set; }
public int SomeMethod(string val) { return 0; }
public static void SomeStaticMethod() { }
}
// The wrapper class to use as a pseudo base class for ThirdPartyClass
public class BaseClass
{
private ThirdPartyClass _obj;
public BaseClass(int i) { _obj = new ThirdPartyClass(i); }
public int SomeProperty
{
get { return _obj.SomeProperty; }
set { _obj.SomeProperty = value; }
}
public int SomeMethod(string val) { return _obj.SomeMethod(val); }
public static SomeStaticMethod() { ThirdPartyClass.SomeStaticMethod(); }
}
// The child class that inherits from the "base" BaseClass
public class ChildClass : BaseClass
{
}
First of all, this might be a logical problem. What if you are going to extend a sealed class? Or Int32 class? Delegate?
Anyway, the way I recommend is to create an interface and implement all the functions you need in the subclass.
I am having 2 classes, both having a same method(name + type +behavior) and a same property (name + type)
public class Country
{
public string Name { get; set; }
public void DisplayName()
{
Console.WriteLine(this.Name);
}
}
public class Person
{
public string Name { get; set; }
public void DisplayName()
{
Console.WriteLine(this.Name);
}
}
-- Person and Country classes are not allowed to inherit
In the above code you can see Person class has similar method(DisplayName) like Country class. I am looking for a way so that both classes can share the same method codes, i want to do this because in my real codes- Method which i want to share is very big and whenever i change code in one class i have to copy paste it in other class too. That i feel is not the correct way.
Please suggest how to resolve this problem.
You say they cannot inherit from a common base class, but you could add an interface, right? I suggest giving them each a common interface. Then define an extension method for that interface. The method will appear for each of them in VS.
(Assumption: this will work if the class members accessed by the extension methods are public or internal.)
interface IDisplayable
{
string Name {get; set;}
}
public class Country : IDisplayable
{
public string Name { get; set; }
}
public class Person : IDisplayable
{
public string Name { get; set; }
}
public static void DisplayName(this iDisplayable d)
{
return doSomeDisplayLogic(d.Name);
}
. . . And in the same class as your extension method, define (not as an extension method) a function doSomeDisplayLogic to do your common logic. (first-time gotcha: make sure the extension method is in the same Namespace or the its namespace is also included in the calling code.)
I don't know if you're new to extension methods or not. They are very powerful. (And like many powerful features, they can be abused). An extension method on an interface seems crazy at first, until you get straight in your head how extension methods really work. LINQ wouldn't work without this!
Update: I see your comment above that the classes can't inherit from a common class, because they are already inheriting from a common class (which I assume can't be messed with too much). I would like to point out an Option 2, based on this: Creating a new class that Country/Person/etc. will inherit from, that itself inherits from the existing common parent class. The existing base class would become a grandparent class, so to speak. This would become more the route to go if Country and Person have other common characteristics besides this DisplayName method. If DisplayName is all you're after, the Interface/Extension pattern might be better.
Define an interface
public interface INameable
{
string Name {get;}
}
then add an extension
public static class INameableExt
{
public static void DisplayName(this INameable n)
{
// do your thing
}
}
I would suggest to avoid Extension Methods in some cases, you can ran into a problem when you need slightly a different implementation for both classes and then you have to design a more generic solution, EM can cause the same issues like multiple inheritance does.
As more generic OOD solution I would suggest to extract this behaviour into a separate service class abstracted by an interface:
public interface IDisplayService()
{
void Display();
}
Then implement it and inject into both classes via constructor.
Also, instead of introducing the interfaces and new classes you can inject Action or Func<> via constructor or even property and then call this method by invoking an injected in delegate.
You could create either a static utility method DisplayName() that you pass the data needed for display, or use composition and move all properties and corresponding methods such as DisplayName() in a separate class - then use an instance of this class from both Country and Person.
You could implement a strategy pattern:
class DisplayNameStrategy<T> {
private readonly Func<T, string> nameSelector;
public void DisplayNameStrategy(Func<T, string> nameSelector) {
this.nameSelector = nameSelector;
}
public void abstract DisplayName(T t);
}
class WriteToConsoleDisplayNameStrategy<T> : DisplayNameStrategy<T> {
public void WriteToConsoleDisplayNameStrategy(Func<T, string> nameSelector)
: base(nameSelector) { }
public override void DisplayName(T t) {
Console.WriteLine(this.nameSelector(t));
}
public class Person {
private readonly DisplayNameStrategy<Person> displayNameStrategy =
new WriteToConsoleDisplayNameStrategy<Person>(x => x.Name);
public string Name { get; set; }
public void DisplayName() {
this.displayNameStrategy(this);
}
}
Note: it's probably better to inject the concrete strategy.
You could use composition: define an interface, a class that implements it, and then have Person and Country implement the interface by calling methods on the implementation class:
// the interface
public interface IName {
string Name { get; set; }
void DisplayName();
}
// a class that implements the interface with actual code
public class NameImpl : IName {
public string Name { get; set; }
public void DisplayName() {
Console.WriteLine(this.Name);
}
}
public class Country : IName {
// instance of the class that actually implements the interface
IName iname = new NameImpl();
// forward calls to implementation
public string Name {
get { return iname.Name; }
set { iname.Name = value; }
}
public void DisplayName() {
// forward calls to implementation
iname.DisplayName();
}
}
What I THINK you are asking for is multiple class inheritance which is not allowed in C#. (but can be with C++ which you are NOT doing).
All the others have identified doing an INTERFACE solution, and probably the best way to go. However, from your description, you have a SINGLE BLOCK of code that is identical regardless of the type of object being a person or a business. And your reference to a huge block of code, you don't want to copy/paste that same exact code among all the other classes that may be intended to use similar common "thing" to be done.
For simple example, you have a functionality that builds out a person's name and address (or business name and address). You have code that is expecting a name and up to 3 address lines, plus a city, state, zip code (or whatever else). So, the formatting of such name/address information is the same for a person vs a business. You don't want to copy this exact method over and over between the two. However, each individual class still has its own things that it is responsible for.
I know its a simple example for context, but I think gets the point across.
The problem with just defining an Interface is that it won't allow you to actually implement the CODE you are referring to.
From your sample, I would consider doing a combination of things.. Create a static class with methods on it that you might want as "globally" available. Allow a parameter to be passed into it of an instance of a class that has a type of interface all the others have expressed that will guarantee the incoming object has all the "pieces" of properties / methods you are expecting, and have IT operate on it as needed. Something like
public interface ITheyHaveInCommon
{
string Name;
string GetOtherValue();
int SomethingElse;
}
public class Person : ITheyHaveInCommon
{
// rest of your delcarations for the required contract elements
// of the ITheyHaveInCommon interface...
}
public class Country : ITheyHaveInCommon
{
// rest of your delcarations for the required contract elements
// of the ITheyHaveInCommon interface...
}
public static class MyGlobalFunctions
{
public static string CommonFunction1( ITheyHaveInCommon incomingParm )
{
// now, you can act on ANY type of control that uses the
// ITheyHaveInCommon interface...
string Test = incomingParm.Name
+ incomingParm.GetOtherValue()
+ incomingParm.SomethingElse.ToString();
// blah blah with whatever else is in your "huge" function
return Test;
}
}
warning: lots of untested code here, wild guessing mostly since i disagree with the base assumption "no inheritance".
something like this should help you. create a new static class and paste your code in here.
public static class Display
{
public static void DisplayName<T>(T obj)
{
if ((T is Person) || (T is Country) || (T is whateveryouwant))
{
//do stuff
}
}
}
in your classes, refactor ShowDisplayName() to call that with "this" as parameter.
...
public void DisplayName()
{
DisplayName(this);
}
...
I wonder why your classes are not allowed to inherit it from a base class, since that's imho the right-est way to solve this.
A couple of options:
Make both classes implement an interface for the common members (Name) and add an extension method for the behaviour (or just a normal static method)
Create methods which take an instance and a lambda exppession to access the comment members, e.g.
public static void Display<T>(T item, Func<T, string> nameGetter)
You'd then call it with (say)
DisplayHelper.Display(person, p => p.Name);
The interface solution is the cleaner one, but using a delegate is more flexible - you don't need to be able to change the classes involved, and you can cope with small variations (e.g. PersonName vs FooName vs Name)
You can define that big method in a separate class and then call the method in both the above classes. For a static method, you can call the method using classname.methodname() syntax.
For a non static method, you will have to do this:
classname obj=new classname();
obj.methodname();
We define interface as below:
interface IMyInterface
{
void MethodToImplement();
}
And impliments as below:
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
instead of creating a interface , why can we use the function directly like below :-)
class InterfaceImplementer
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Any thoughts?
You are not implementing the interface in the bottom example, you are simply creating an object of InterfaceImplementer
EDIT: In this example an interface is not needed. However, they are extremely useful when trying to write loosely coupled code where you don't have to depend on concrete objects. They are also used to define contracts where anything implementing them has to also implement each method that it defines.
There is lots of information out there, here is just a brief intro http://www.csharp-station.com/Tutorials/Lesson13.aspx
If you really want to understand more about interfaces and how they can help to write good code, I would recommend the Head First Design Patterns book. Amazon Link
instead of creating a interface , why
can we use the function directly like
below
Are you asking what the point of the interface is?
Creating an interface allows you to decouple your program from a specific class, and instead code against an abstraction.
When your class is coded against an interface, classes that use your class can inject whichever class they want that implements this interface. This facilitates unit testing since not-easily-testable modules can be substituted with mocks and stubs.
The purpose of the interface is for some other class to be able to use the type without knowing the specific implementation, so long as that type conforms to a set of methods and properties defined in the interface contract.
public class SomeOtherClass
{
public void DoSomething(IMyInterface something)
{
something.MethodToImplement();
}
}
public class Program
{
public static void Main(string[] args)
{
if(args != null)
new SomeOtherClass().DoSomething(new ImplementationOne());
else
new SomeOtherClass().DoSomething(new ImplementationTwo());
}
}
Your example doesn't really follow that pattern, however; if one that one class implements the interface, then there really isn't much of a point. You can call it either way; it just depends on what kind of object hierarchy you have and what you intend to do for us to say whether using an interface is a good choice or not.
To sum: Both snippets you provide are valid code options. We'd need context to determine which is a 'better' solution.
Interfaces are not required, there is nothing wrong with the last section of code you posted. It is simply a class and you call one of it's public methods. It has no knowledge that an interface exists that this class happens to satisfy.
However, there are advantages:
Multiple Inheritance - A class can only extend one parent class, but can implement any number of interfaces.
Freedom of class use - If your code is written so that it only cares that it has an instance of SomethingI, you are not tied to a specific Something class. If tomorrow you decide that your method should return a class that works differently, it can return SomethingA and any calling code will not need to be changed.
The purpose of interfaces isn't found in instantiating objects, but in referencing them. Consider if your example is changed to this:
static void Main()
{
IMyInterface iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
Now the iTmp object is of the type IMyInterface. Its specific implementation is InterfaceImplementer, but there may be times where the implementation is unimportant (or unwanted). Consider something like this:
interface IVehicle
{
void MoveForward();
}
class Car : IVehicle
{
public void MoveForward()
{
ApplyGasPedal();
}
private void ApplyGasPedal()
{
// some stuff
}
}
class Bike : IVehicle
{
public void MoveForward()
{
CrankPedals();
}
private void CrankPedals()
{
// some stuff
}
}
Now say you have a method like this somewhere:
void DoSomething(IVehicle)
{
IVehicle.MoveForward();
}
The purpose of the interface becomes more clear here. You can pass any implementation of IVehicle to that method. The implementation doesn't matter, only that it can be referenced by the interface. Otherwise, you'd need a DoSomething() method for each possible implementation, which can get messy fast.
Interfaces make it possible for an object to work with a variety of objects that have no common base type but have certain common abilities. If a number of classes implement IDoSomething, a method can accept a parameter of type IDoSomething, and an object of any of those classes can be passed to it. The method can then use all of the methods and properties applicable to an IDoSomething without having to worry about the actual underlying type of the object.
The point of the interface is to define a contract that your implementing class abides by.
This allows you to program to a specification rather than an implementation.
Imagine we have the following:
public class Dog
{
public string Speak()
{
return "woof!";
}
}
And want to see what he says:
public string MakeSomeNoise(Dog dog)
{
return dog.Speak();
}
We really don't benefit from the Interface, however if we also wanted to be able to see what kind of noise a Cat makes, we would need another MakeSomeNoise() overload that could accept a Cat, however with an interface we can have the following:
public interface IAnimal
{
public string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "woof!";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "meow!";
}
}
And run them both through:
public string MakeSomeNoise(IAnimal animal)
{
return animal.Speak();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I cannot get my head around how to use interfaces and why they are needed. Can someone please show me a simple example?
interface IFlyable
{
void Fly();
}
class Bird : IFlyable
{
public void Fly() { }
}
class Plane : IFlyable
{
public void Fly() { }
}
List<IFlyable> things = GetBirdInstancesAndPlaneInstancesMixed();
foreach(IFlyable item in things)
{
item.Fly();
}
Bird and Plane have no common base class except Object, but you can see using the same interface we can deal with them grouply in our program, because they have the same "feature": Fly.
public interface ISpeaks
{
string Speak();
}
public class Dog : Mammal, ISpeaks
{
public string Speak() { return "Woof!"; }
}
public class Person : Mammal, ISpeaks
{
public string Speak() { return "Hi!"; }
}
//Notice Telephone has a different abstract class
public class Telephone : Appliance, ISpeaks
{
public Person P { get; set; }
public Telephone(Person p)
{
P = p;
}
public string Speak() { return P.Speak(); }
}
[Test]
public void Test_Objects_Can_Speak()
{
List<ISpeaks> thingsThatCanSpeak = new List<ISpeaks>();
//We can add anything that implements the interface to the list
thingsThatCanSpeak.Add(new Dog());
thingsThatCanSpeak.Add(new Person());
thingsThatCanSpeak.Add(new Telephone(new Person()));
foreach(var thing in thingsThatCanSpeak)
{
//We know at compile time that everything in the collection can speak
Console.WriteLine(thing.Speak());
}
}
This is useful because we can code against the interface rather than implementation and because we can use multiple interfaces on a single class, we are more flexible than if we used an Abstract class.
Interfaces are somehow class definition alike, a sort of contract between the interface and the class implementing it.
An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
A .NET class cannot use multi-inheritance. As such, we rely on interfaces, and a class can implement as much interfaces as you wish. On the contrary, a class inheritance has to be single. For instance:
public class Customer : Person, Company {
}
This code is not allowed in any .NET languages that I know (C#/VB.NET).
To counter this lack, if we may say so, we rely on interfaces.
public interface IPerson {
string Name
string Address
string StateProvince
string ZipPostalCode
string Country
long PhoneNumber
}
public interface ICompany {
string CreditTerm
string BillingAddress
string ShippingAddress
string ContactName
long ContactPhoneNumber
long FaxNumber
}
public class Customer : IPerson, ICompany {
// Properties implementations here.
}
In this way, interfaces are like a workaround somehow to multi-inheritance.
On the other hand, interfaces can be used as a contract for methods. Let's say you got a method that take an ICompany as an input parameter. You are now sure to have the properties defined in the ICompany interface to perform your work within the method.
public BillCompany(ICompany company) {
// Bill company here...
}
Then, your Customer class correspond to what you are expecting, since it implements the ICompany interface.
Let's make another class, whose definition would only implement the IPerson interface.
public class Individual : IPerson {
// Interface implementation here...
}
Then, your BillCompany() method could not accept an instance of the Individual class, as it doesn't show requirements (properties, etc.) for a company.
In short, interfaces are a good way to bind by contract your methods to what will be accepted, like inheritance.
There are indeed some precautions to take while working with Interfaces, a change to an interface will break your code, as an enforcing rule to implement the new member within all implementing classes, which class inheritance does not.
Does this help?
I like this blog post that I read the other day: http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/
Many people, myself included, have created interfaces that have a 1 to 1 mapping to the class they are representing but this is not always a good thing and that article explains why.
An interface is useful when you have a given contract you want an object to fulfill but you don't really care about how they fulfill it. That's an implementation detail left to the class itself.
So let's say you have a method that's job is to process save requests. It does not perform the actual act of saving, it just processes the requests. As a result, it can take a List<ICanSave>, where ICanSave is an interface. The objects in that list can be any type that implements that interface. It can be a mix, or it can contain just one type. You're just concerned that it implements the interface.
public interface ICanSave
{
void Save();
}
In your method, you might have something simple like
public void SaveItems(List<ICanSave> items)
{
foreach (var item in items)
{
item.Save();
}
}
How are those items being saved? You don't care! That, again, is an implementation detail for the class implementing the interface. You just want whatever class that enters the method to have that ability.
You could have a class that implements the interface that persists data to the file system. Another might save to a database. Another may call some external service. Etc. That's left for the author of the class to decide. You might even have a stubbed class for a unit test that does nothing at all.
That's just one use-case scenario, there are many others, several in the BCL. IEnumerable<T> is a good one, it is implemented by things such as ICollection<T> and IList<T>, which are in turn implemented by concrete types such as Array and List<T>. It's the interface which makes many of the programming constructs you may be accustomed to useful, such as LINQ. LINQ doesn't care about the actual implementation* of the class, it just wants to be able to enumerate it and perform the proper filtering and/or projection.
IDisposable is another good BCL example. You want to know that a class needs to clean up after itself. What specifically it needs to clean up is left up to the class, but by nature of it implementing IDisposable, you know it needs to clean up after itself, so you preferrably wrap its use in a using statement or you manually ensure that you call .Dispose once you've finished working with the object.
*LINQ actually does optimize for some interfaces.
Simple example of interface Animal with two implementation of class animal (you have an unique description for animal and many implementation in class dog, cat...)
public interface IAnimal
{
string GetDescription();
}
class Cat : IAnimal
{
public string GetDescription()
{
return "I'm a cat";
}
}
class Program
{
static void Main(string[] args)
{
Cat myCat = new Cat();
Console.WriteLine(myCat.GetDescription());
}
}
"I've got a bunch of classes here that I want to treat the same way, for a certain amount of functionality."
So, you write a contract.
Real-world example: I'm writing a wizard. It has a bunch of pages, some of which (but not all) are UserControls. They all need a common set of operations, so the controlling class can treat them all the same. So I have an IPage interface that they all implement, with operations like initializing the page, saving the user's choices, et cetera. In my controller, I simply have a List, and don't have to know what page does what; I simply call the interface's Save()s and Initialize()s.
Here is the main points of Interface,
1.We can call same method using different classes with different out put of same methods.
Simple Example:
class Mango : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Mango refDemo = new Mango();
refDemo.mymethod();
Orange refSample = new Orange();
refSample.mymethod();
}
public void mymethod()
{
System.Console.WriteLine("In Mango : mymethod");
}
}
interface abc
{
void mymethod();
}
class Orange : abc
{
public void mymethod()
{
System.Console.WriteLine("In Orange : mymethod");
}
}
2.can call same method using same interface with different classes.
class Mango : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
abc refabc = new Mango();
refabc.mymethod();
abc refabd = new Orange();
refabd.mymethod();
Console.ReadLine();
}
public void mymethod()
{
System.Console.WriteLine("In Mango : mymethod");
}
}
interface abc
{
void mymethod();
}
class Orange : abc
{
public void mymethod()
{
System.Console.WriteLine("In Orange : mymethod");
}
}
Well from MSDN, "An interface defines a contract. A class or struct that implements an interface must adhere to its contract."
On this page, there are several examples of what an interface looks like, how a class inherits from an interface and a full blown example of how to implement an interface.
Hope this helps out some.