I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don't understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
MyNiftyClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something nifty
}
}
MyOddClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something odd
}
}
And now you have:
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
public void ThisMethodShowsHowItWorks(IMyInterface someObject)
{
someObject.CallSomeMethod();
}
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
public void AnotherClass()
{
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
// Pass in the nifty class to do something nifty
this.ThisMethodShowsHowItWorks(nifty);
// Pass in the odd class to do something odd
this.ThisMethodShowsHowItWorks(odd);
}
EDIT
This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?
That is, why use:
IMyInterface foo = new MyConcreteClass();
in preference to:
MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
public void AMethod()
{
// Why use this?
IMyInterface foo = new MyConcreteClass();
// Why not use this?
MyConcreteClass bar = new MyConcreteClass();
}
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
I typically inject dependencies so the polymorphism is needed
Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this:
public void AMethod(string input)
{
IMyInterface foo;
if (input == "nifty")
{
foo = new MyNiftyClass();
}
else
{
foo = new MyOddClass();
}
foo.CallSomeMethod();
}
Because this:
public void ReadItemsList(List<string> items);
public void ReadItemsArray(string[] items);
can become this:
public void ReadItems(IEnumerable<string> items);
Edit
Think of it like this:
You have to be able to do this.
rather than:
You have to be this.
Essentially this is a contract between the method and it's callers.
Using interface variables is the ONLY way to allow handler methods to be written which can accept data from objects that have different base classes.
This is about as clear as anyone is going to get.
An interface is used so you do not need to worry about what class implements the interface. An example of this being useful is when you have a factory method that returns a concrete implementation that may be different depending on the environment you are running in. It also allows an API designer to define the API while allowing 3rd parties to implement the API in any way they see fit. Sun does this with it's cryptographic API's for Java.
public interface Foo {
}
public class FooFactory {
public static Foo getInstance() {
if(os == 'Windows') return new WinFoo();
else if(os == 'OS X') return new MacFoo();
else return new GenricFoo();
}
}
Your code that uses the factory only needs to know about Foo, not any of the specific implementations.
I was in same position and took me few days to figure out why do we have to use interface variable.
IDepartments rep = new DepartmentsImpl();
why not
DepartmentsImpl rep = new DepartmentsImpl();
Imagine If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.
class Test
{
static void Main()
{
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
// The following lines all call the same method.
sc.Paint();
ctrl.Paint();
srfc.Paint();
}
}
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
IControl c = new SampleClass();
ISurface s = new SampleClass();
s.Paint();
Please do correct me if i am wrong as i am still learning this Interface concept.
Lets say you have class Boat, Car, Truck, Plane.
These all share a common method TakeMeThere(string destination)
You would have an interface:
public interface ITransportation
{
public void TakeMeThere(string destination);
}
then your class:
public class Boat : ITransportation
{
public void TakeMeThere(string destination) // From ITransportation
{
Console.WriteLine("Going to " + destination);
}
}
What you're saying here, is that my class Boat will do everything ITransportation has told me too.
And then when you want to make software for a transport company. You could have a method
Void ProvideServiceForClient(ITransportation transportationMethod, string whereTheyWantToGo)
{
transportationMethod.TakeMeThere(whereTheyWantToGo); // Cause ITransportation has this method
}
So it doesn't matter which type of transportation they want, because we know it can TakeMeThere
This is not specific to C#,so i recommend to move to some othere flag.
for your question,
the main reason why we opt for interface is to provide a protocol between two components(can be a dll,jar or any othere component).
Please refer below
public class TestClass
{
static void Main()
{
IMyInterface ob1, obj2;
ob1 = getIMyInterfaceObj();
obj2 = getIMyInterfaceObj();
Console.WriteLine(ob1.CallSomeMethod());
Console.WriteLine(obj2.CallSomeMethod());
Console.ReadLine();
}
private static bool isfirstTime = true;
private static IMyInterface getIMyInterfaceObj()
{
if (isfirstTime)
{
isfirstTime = false;
return new ImplementingClass1();
}
else
{
return new ImplementingClass2();
}
}
}
public class ImplementingClass1 : IMyInterface
{
public ImplementingClass1()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return true;
}
#endregion
}
public class ImplementingClass2 : IMyInterface
{
public ImplementingClass2()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return false;
}
#endregion
}
public interface IMyInterface
{
bool CallSomeMethod();
}
Here the main method does not know about the classes still it is able to get different behaviour using the interface.
The purpose of the Interface is to define a contract between several objects, independent of specific implementation.
So you would usually use it when you have an Intrace ISomething, and a specific implementation
class Something : ISomething
So the Interface varialbe would come to use when you instantiate a contract:
ISomething myObj = new Something();
myObj.SomeFunc();
You should also read interface C#
Update:
I will explaing the logic of using an Interface for the variable and not the class itself by a (real life) example:
I have a generic repositor interace:
Interface IRepository {
void Create();
void Update();
}
And i have 2 seperate implementations:
class RepositoryFile : interface IRepository {}
class RepositoryDB : interface IRepository {}
Each class has an entirely different internal implementation.
Now i have another object, a Logger, that uses an already instansiated repository to do his writing. This object, doesn't care how the Repository is implemented, so he just implements:
void WriteLog(string Log, IRepository oRep);
BTW, this can also be implemented by using standard classes inheritance. But the difference between using interfaces and classes inheritance is another discussion.
For a slightly more details discussion on the difference between abstract classes and interfaces see here.
Say, for example, you have two classes: Book and Newspaper. You can read each of these, but it wouldn't really make sense for these two to inherit from a common superclass. So they will both implement the IReadable interface:
public interface IReadable
{
public void Read();
}
Now say you're writing an application that will read books and newspapers for the user. The user can select a book or newspaper from a list, and that item will be read to the user.
The method in your application that reads to the user will take this Book or Newspaper as a parameter. This might look like this in code:
public static void ReadItem(IReadable item)
{
item.Read();
}
Since the parameter is an IReadable, we know that the object has the method Read(), thus we call it to read it to the user. It doesn't matter whether this is a Book, Newspaper, or anything else that implements IReadable. The individual classes implement exactly how each item will be read by implementing the Read() method, since it will most likely be different for the different classes.
Book's Read() might look like this:
public void Read()
{
this.Open();
this.TurnToPage(1);
while(!this.AtLastPage)
{
ReadText(this.CurrentPage.Text);
this.TurnPage();
}
this.Close();
}
Newspaper's Read() would likely be a little different:
public void Read()
{
while(!this.OnBackPage)
{
foreach(Article article in this.CurrentPage.Articles)
{
ReadText(article.Text);
}
}
}
The point is that the object contained by a variable that is an interface type is guaranteed to have a specific set of methods on it, even if the possible classes of the object are not related in any other way. This allows you to write code that will apply to a variety of classes that have common operations that can be performed on them.
No, it is not possible. Designers did not provide a way. Of course, it is of common sense also. Because interface contains only abstract methods and as abstract methods do not have a body (of implementation code), we cannot create an object..
Suppose even if it is permitted, what is the use. Calling the abstract method with object does not yield any purpose as no output. No functionality to abstract methods.
Then, what is the use of interfaces in Java design and coding. They can be used as prototypes from which you can develop new classes easily. They work like templates for other classes that implement interface just like a blue print to construct a building.
I believe everyone is answering the polymorphic reason for using an interface and David Hall touches on partially why you would reference it as an interface instead of the actual object name. Of course, being limited to the interface members etc is helpful but the another answer is dependency injection / instantiation.
When you engineer your application it is typically cleaner, easier to manage, and more flexible if you do so utilizing dependency injection. It feels backwards at first if you've never done it but when you start backtracking you'll wish you had.
Dependency injection normally works by allowing a class to instantiate and control the dependencies and you just rely on the interface of the object you need.
Example:
Layer the application first. Tier 1 logic, tier 2 interface, tier 3 dependency injection. (Everyone has their own way, this is just for show).
In the logic layer you reference the interfaces and dependency layer and then finally you create logic based on only the interfaces of foreign objects.
Here we go:
public IEmployee GetEmployee(string id)
{
IEmployee emp = di.GetInstance<List<IEmployee>>().Where(e => e.Id == id).FirstOrDefault();
emp?.LastAccessTimeStamp = DateTime.Now;
return emp;
}
Notice above how we use di.GetInstance to get an object from our dependency. Our code in that tier will never know or care about the Employee object. In fact if it changes in other code it will never affect us here. If the interface of IEmployee changes then we may need to make code changes.
The point is, IEmployee emp = never really knows what the actual object is but does know the interface and how to work with it. With that in mind, this is when you want to use an interface as opposed to an object becase we never know or have access to the object.
This is summarized.. Hopefully it helps.
This is a fundamental concept in object-oriented programming -- polymorphism. (wikipedia)
The short answer is that by using the interface in Class A, you can give Class A any implementation of IMyInterface.
This is also a form of loose coupling (wikipedia) -- where you have many classes, but they do not rely explicitly on one another -- only on an abstract notion of the set of properties and methods that they provide (the interface).
Related
I have searched for an answer to accomplish this, but I haven't found anything: I want an interface's method to return an object of the type of the class which implemented it. For example:
interface InterfaceA {
public static returnValue getObjectFromDatabase(); //What do i need to put as returnValue?
}
Then, if I have two classes (for example, ClassA and ClassB) that implement it, I would like to have:
ClassA obj1 = ClassA.getObjectFromDatabase(); //return object of class ClassA
ClassB obj2 = ClassB.getObjectFromDatabase(); //return object of class ClassB
Thank you, in advance.
What you want to do here won't work for two reasons:
Interfaces can't have static members
Interfaces need to specify the return types of their methods. An interface shouldn't know the types of all the members implementing it, that defeats the point and in many cases would be unachievable.
Moreover, if you did manage to do this, it still wouldn't be good design, because it violates the single responsibility principle. You can find plenty of information on this by googling it or looking around this site, but the idea- as indicated by the name- is that a class should only have a single purpose which it is responsible for.
So imagine that your class was, for example, an Employee class. That class has a pretty clear responsibility, it should be responsible for holding information and functionality related to an Employee in a company. It might have members like FirstName, GivePromotion(), etc. So it'd be strange to now make this class also take responsibility for its own database access.
So how this is achieved would be with another class which is responsible for retrieving objects from the database. One common design pattern for this is the repository pattern. You'll also probably want to take advantage of generics. So you repository interface might look like:
public interface IRepository<T>
{
T GetFromDatabase()
}
Which you can then implement with a generic repository:
public class Repository<T> : IRepository<T>
{
T GetFromDatabase()
{
//Your actual code for database retrieval goes here
}
}
Or, if the database retrieval code is very different for some or all classes, you can implement with a specific repository:
public class EmployeeRepository : IRepository<Employee>
{
Employee GetFromDatabase()
{
//Your actual code for database retrieval goes here
}
}
One approach is to use generics:
class Program
{
interface MyInterface<SomeType>
{
SomeType getObjectFromDatabase ();
}
class A : MyInterface<A> { public A getObjectFromDatabase () { return new A (); } }
class B : MyInterface<B> { public B getObjectFromDatabase () { return new B (); } }
class Program2
{
static void Main ()
{
A a1, a2;
a1 = new A ();
a2 = a1.getObjectFromDatabase ();
B b1, b2;
b1 = new B ();
b2 = b1.getObjectFromDatabase ();
}
}
}
I want an interface's method to return an object of the type of the class which > implemented it
You seem to miss the point of interfaces: an Interface shouldn't have any knowledge about its implementers. Interface exposes contracts and that's it.
Also, from your example, I can see that you are trying to create a static method but interfaces and static are far away from each other. Interfaces are tied with instances, not the type.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interfaces: Why can't I seem to grasp them?
to work with a library I just found I need to implement a few interfaces first. But some methods seem to be asking for objects that have the type of some interfaces...
And if I have an interface called MyInterface I can write things like :
MyInterface shoe;
It does not really make sense to me. Can somebody teach me this concept ?
I read this : http://www.dotnetperls.com/interface but it did not really help, I think this concept is a bit more complex than what is presented here.
Thanks !
edit :
For those who wonder, I am not new to Interfaces but it is the first time I ran into such a use of them. And for those downgrading my question, I did search but was unlucky apparently.
A simple explanation: A class is like a company. If it claims to be a sales company, it has to provide sales services. It it claims to be a train factory, it has to be able to make trains.
If the national railroads wants to buy trains, it can use any company that can produce trains.
An interface describes what a class has to be able to do. It is like a contract. Each class that wants to have an interface has to fulfill that contract and be able to do what the contract says it has to do. Class instances can perform actions through class methods.
However, the contract doesn't say how the class should do it. So a class can implement the functionality however it wants, or in other words, implement the interface.
public Train
{
private price;
public Train(float price) { this.price = price; }
}
public IMyInterface
{
Train MakeTrain();
}
public ExpensiveTrainFactory : ITrainProducer
{
// make a luxury, expensive train
public Train MakeTrain() { return new Train(4000.0); }
}
public CheapTrainFactory : ITrainProducer
{
// make a cheap train
public Train MakeTrain() { return new Train(500.0); }
}
public NationalRailways
{
List<Train> trains;
public NationalRailways()
{
this.trains = new List<Train>();
}
public Train BuyTrain(ITrainProducer factory)
{
// you can call MakeTrain() because the ITrainProducer guarantees that it can make trains
trains.Add(factory.MakeTrain());
}
}
and then in your code:
NationalRailways railway = new NationalRailways();
ExpensiveTrainFactory expFactory = new ExpensiveTrainFactory();
CheapTrainFactory cheapFactory = new CheapTrainFactory();
// expFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer)
railways.BuyTrain(expFactory);
// cheapFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer) as well
railways.BuyTrain(cheapFactory);
You can declare an Interface, like in your example. However you can not instantiate one.
MyInterface shoe = new MyInterface ();
The above is not legal code. Since an Interface just describes a contract, it has no implementation details, this is left to the client code (you). Therefore it makes no sense to be able to create actual instances of MyInterface.
What you can do, is have a class SomeClass, implement the MyInterface contract:
SomeClass: MyInterface
{
//implement the methods of MyInterface. All of them, to fulfill the contract.
}
Then you can do things like:
MyInterface shoe = new SomeClass();
Since SomeClass implements the MyInterface contract, the above is legal. You can create an instance of SomeClass because it contains implementation details.
Then you can build on this and create more classes which implement MyInterface.
The beauty of this is that you can have a method for example:
void someMethod (MyInterface test)
{
}
You can pass this method the SomeClass object or any other class you created which implements MyInterface.
Then inside this method, you can call methods that the contract contains without knowing the exact object which has been passed to you. This makes writing future code easier. You can create new objects and so long as they implement MyInterface, it is valid to pass this object to someMethod without changing the declaration of the method.
You are correct, you can't directly create an instance of an interface. However, you can create an instance of some type that implements that interface.
Say I have an interface
public IMyInterface
{
void DoSomething();
}
(note: usually you start the name of an interface with "I")
Plus I have a class
public MyClass: IMyInterface
{
public void DoSomething() { ... }
}
Then I can do
IMyInterface something = new MyClass();
although you often call some (factory) method to return some class that implements that interface instead of directly doing a new.
By using the interface as the type of your variable, you specify that you are only interested in the methods and properties specified there.
In C#, each value has two different types: apparent type and actual type. The apparent type is the type of the variable holding the value, and the actual type comes from the constructor used to create the value. Let's say we have the following class:
class MyClass : BaseClass, IMyInterface {
/* ... */
}
Then all the following declarations are valid:
object obj1 = new MyClass();
IMyInterface obj2 = new MyClass();
BaseClass obj3 = new MyClass();
MyClass obj4 = new MyClass();
The apparent and actual types are as follows:
object obj1 = new MyClass(); /* apparent: object, actual: MyClass */
IMyInterface obj2 = new MyClass(); /* apparent: IMyInterface, actual: MyClass */
BaseClass obj3 = new MyClass(); /* apparent: BaseClass, actual: MyClass */
MyClass obj4 = new MyClass(); /* apparent: MyClass, actual: MyClass */
When you manipulate an object (call its methods, etc), you do it assuming the object has its apparent type - you can't call any class-specific methods of an object. The apparent type dictates the interface of the object visible outside the object.
What actually happens under the hood is done according to the object's actual type - for example, if you override the ToString method of your class, the overridden method is called in the following code:
object obj = new MyClass();
Console.WriteLine(obj.ToString());
The actual type dictates how the object's functionality is implemented.
Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me use same example as per your link with bit of modification:
using System;
interface IPerl
{
void Read();
}
class Test : IPerl
{
public void Read()
{
Console.WriteLine("Read Test");
}
}
class Test1 : IPerl
{
public void Read()
{
Console.WriteLine("Read Test1");
}
}
class Program
{
static void Main()
{
IPerl perl = new Test(); // Create instance of Test.
perl.Read(); // Call method on interface output will be different then Test1.
perl = new Test1(); // Create instance of Test1.
perl.Read(); // Call method on interface output will be different then Test.
}
}
Output:
"Read Test"
"Read Test1"
I hope this would help.
Thanks Ankur
What Interfaces Are
Interfaces basically define a blueprint for a class or a struct. The programmed definition of an interface looks very similar to a class, but nothing is implemented. Interfaces define the properties, methods, events, and indexers, but the interface does not define the implementation of any of these. It just declares their existence. Interfaces will not actually define any functionality. They just define ways in which interactions with a class takes place.
What Interfaces Are Not
Interfaces should not be confused with inheritance. They are two very different things. Inheritance will define a lot of the implementation and is used for code reuse. Interfaces are merely a definition for how communication with the implementing classes must take place. It is like a written contract. A class "signing" the contract will agree to perform certain specified actions in any way it wishes, but it must perform the specified actions.
When to Use Interfaces
Interfaces allow us to create nice layouts for what a class is going to implement. Because of the guarantee the interface gives us, when many components use the same interface it allows us to easily interchange one component for another which is using the same interface. Dynamic programs begin to form easily from this.
For more information visit this post about Understanding_Interfaces_in_C#
We are trying to build some kind of a layer above the DAL in order to expose an interface of a certain repository methods using generics.
For example:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public void Main()
{
Exposer<A>.Do_A();
Exposer<B>.Do_B();
}
Is it possible to do that ?
Tecnically, that isn't a "single class", since Exposer<A> is a different Type to Exposer<B>; however, ultimately, this doesn't look much different to most IoC/DI containers... if this was, say, StructureMap (purely for an example), you might consider:
container.GetInstance<A>().Do_A();
container.GetInstance<B>().Do_B();
you would, of course, need to configure the container to know where the concrete A and B implementations are coming from! Which for StructureMap is shown here, but there are plenty to choose from.
If you mean directly, then: no. You cannot have:
class Exposer<T> : T {...} // non-working code to implement the interface T
You can, however, have some class:
class Exposer : A, B {...}
and just cast:
A a = Exposer;
a.Do_A();
B b = Exposer;
b.Do_B();
A type Foo<T> cannot implement (or extend) the actual T, as T is unknown at compile time. What you could do is expose a T as a property, and invoke methods on it. However, as Ondrej wrote, the question may be a little unclear.
Are you describing IoC when you write?
Exposer<A>.Do_A();
Your Exposer class makes me think to StructureMap API:
ObjectFactory.GetInstance<T>().Do_A();
If you want to get rid of the keyword new and get in a generic way an instance for a specified interface, take a look to this article or check StructureMap
To choose which interface implementation you want when consuming a given class, you don't use generics, you just cast the class to the interface:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public class Exposer : A, B
{
public void Do_A() { ; }
public void Do_B() { ; }
}
public void Main()
{
// the casts are redundant here,
// because the interface implementation
// is implicit
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}
If you want to exclude members that are not implementations of members of the given interface, use explicit implementation:
public class Exposer : A, B
{
void A.Do_A() { ; }
void B.Do_B() { ; }
}
public void Main()
{
// the casts are now required;
// otherwise, you'll get a compiler error
// telling you that the method is inaccessible
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}
I m trying to understand Interfaces so that I can implement them in my programs but I m not able to imagine how should i use them.
Also give me some eg of using them with multiple inheritance in C#
A good example for an interface is a repository pattern. Your interface will define methods like Get, GetAll, Update, Delete, etc. No implementation, just function signatures.
Then, you can write a 'concrete' implementation of that class to work with, say, MySQL. Your UI should only refer to the interface, though.
Later, if you decide to change to Microsoft SQL, you write another concrete implementation, but your UI code doesn't have to change (much).
Multiple inheritance doesn't exist in C#, in the sense that you can only inherit from one 'concrete' class; though you can inherit (or 'implement') as many interfaces as you want.
I am writing a video game. In this video game I apply different forces to objects in the game. Thrust forces, impact forces, gravitational forces. While they are calculated differently, they all have the same basic elements. I need to call an update function that will evaluate the force and add the force to the object it's attached to.
So, what I've done is create an IForce interface that has an update function for its signature. All of my forces implement this interface:
public interface IForce
{
void Update(Particle particle, GameTime gameTime);
}
Here is a sample implementation.
public class Spring : IForce
{
private Particle ThisParticle;
private Particle ThatParticle;
private float K;
public Spring(Particle thisParticle, Particle thatParticle, float k)
{
ThisParticle = thisParticle;
ThatParticle = thatParticle;
}
public void Update(Particle particle, GameTime gameTime)
{
float X = Vector3.Length(ThisParticle - ThatParticle);
ThisParticle.Forces.Add(K * X);
}
}
The update function has a simplified spring force update to make it easier to understand.
This helps in a few ways.
I can completely change the way a force is calculated without effecting other parts of my code. I do this all the time. Along the same lines, it is rediculously easy for me to add new forces. As long as it implements the IForce interface I know it will mesh well with my existing code.
Another way it helps is with handling a large number of forces. I have a force registry that has a List of IForce. Since all forces implement that interface and have an Update function it's very easy to update all the forces in my game. When I create the force I add it to the list. Then, I loop through the list and call each elements update function without worrying about what type of force it is and all my forces update.
I use interfaces every day in a lot of different situations. They are fantastic!
Note :Interface is used to restrict and access the methods or events etc from differents classes at any cost, It means we can defined many more methods inside any class but when we are calling methods through Interface means we want only other than restricted methods. In the program below User1 can use Read & Write both but User2 can Write and Execute. See this Program below.........
namespace ExplConsole
{
class Program
{
static void Main ()
{
System.Console.WriteLine("Permission for User1");
User1 usr1 = new Test(); // Create instance.
usr1.Read(); // Call method on interface.
usr1.Write();
System.Console.WriteLine("Permission for User2");
User2 usr2 = new Test();
usr2.Write();
usr2.Execute();
System.Console.ReadKey();
}
}
interface User1
{
void Read();
void Write();
}
interface User2
{
void Write();
void Execute();
}
class Test : NewTest,User1, User2
{
public void Read()
{
Console.WriteLine("Read");
}
public void Write()
{
Console.WriteLine("Write");
}
}
class NewTest
{
public void Execute()
{
Console.WriteLine("Execute");
}
}
}
Output:
Permission for User1
Read
Write
Permission for User2
Write
Execute
Interfaces simply define a contract of the public elements (e.g. properties, methods, events) for your object, not behavior.
interface IDog
{
void WagTail(); //notice no implementation
ISound Speak(); //notice no implementation
}
class Spaniel : IDog
{
public void WagTail()
{
Console.WriteLine("Shook my long, hairy tail");
}
public ISound Speak()
{
return new BarkSound("yip");
}
}
class Terrier : IDog
{
public void WagTail()
{
Console.WriteLine("Shook my short tail");
}
public ISound Speak()
{
return new BarkSound("woof");
}
}
UPDATE
In "real examples" I use interfaces with:
- Unit Testing
- GENERICS (e.g. Repository, Gateway, Settings)
interface Repository<T>{
T Find(Predicate<T>);
List<T> ListAll();
}
interface Gateway<T>{
T GetFrom(IQuery query);
void AddToDatabase(IEntity entityItem);
}
interface Settings<T>{
string Name { get; set; }
T Value { get; set; }
T Default { get; }
}
Here is one (in Java, but this is not important since they're similiar):
In my project I've created simple interface:
public interface Identifiable<T> {
public T getId();
}
Which is simple replacement to some sorts of annotations. The next step: I've made all entity classes implement this interface.
The third step is to write some syntax-sugar-like methods:
public <T> List<T> ids(List<? extends Identifiable<T> entities) { ... }
This was just an example.
The more complex example is something like validation rules: you have some validation engine (probably written by you) and a simple interface for rule:
public interface ValidationRule {
public boolean isValid(...);
}
So, this engine requires the rules to be implemented by you. And of course there will be multiple inheritance since you'll certainly wish more then a single rule.
Multiple inheritance is about having a class be usable in multiple situations: [pseudo code]
interface Shape {
// shape methods like draw, move, getboundingrect, whatever.
}
interface Serializable {
// methods like read and write
}
class Circle : public Shape, public Serializable {
// TODO: implement Shape methods
// TODO: implement Serializable methods
}
// somewhere later
{
Circle circle;
// ...
deserializer.deserialize(circle);
// ...
graphicsurface.draw(circle);
// ...
serializer.serialize(circle);
}
The idea is that your Circle class implements two different interfaces that are used in very different situations.
Sometimes being too abstract just gets in the way and referring to implementation details actually clarifies things. Therefore, I'll provide the close to the metal explanation of interfaces that made me finally grok them.
An interface is just a way of declaring that a class implements some virtual functions and how these virtual functions should be laid out in the class's vtable. When you declare an interface, you're essentially giving a high-level description of a virtual function table to the compiler. When you implement an interface, you're telling the compiler that you want to include the vtable referred to by that interface in your class.
The purpose of interfaces is that you can implicitly cast a class that implements interface I to an instance of interface I:
interface I {
void doStuff();
}
class Foo : I {
void doStuff() {}
void useAnI(I i) {}
}
var foo = new Foo();
I i = foo; // i is now a reference to the vtable pointer for I in foo.
foo.useAnI(i); // Works. You've passed useAnI a Foo, which can be used as an I.
The simple answer, in my opinion, and being somewhat new to interfaces myself is that implementing an interface in a class essentially means: "This class MUST define the functions (and parameters) in the interface".
From that, follows that whenever a certain class implements the interface, you can be sure you are able to call those functions.
If multiple classes which are otherwise different implement the same interface, you can 'cast' them all to the interface and call all the interface functions on them, which might have different effects, since each class could have a different implementation of the functions.
For example, I've been creating a program which allows a user to generate 4 different kinds of maps. For that, I've created 4 different kind of generator classes. They all implement the 'IGenerator' interface though:
public interface IGenerator {
public void generateNow(int period);
}
Which tells them to define at least a "public generateNow(int period)" function.
Whatever generator I originally had, after I cast it to a "IGenerator" I can call "generateNow(4)" on it. I won't have to be sure what type of generator I returned, which essentially means, no more "variable instanceof Class1", "variable instanceof Class2" etc. in a gigantic if statement anymore.
Take a look at something you are familiar with - ie a List collection in C#. Lists define the IList interface, and generic lists define the IList interface. IList exposes functions such as Add, Remove, and the List implements these functions. There are also BindingLists which implement IList in a slightly different way.
I would also recommend Head First Design Patterns. The code examples are in Java but are easily translated into C#, plus they will introduce you to the real power of interfaces and design patterns.
This question already has answers here:
C# Interfaces. Implicit implementation versus Explicit implementation
(13 answers)
Closed 7 years ago.
What's the difference between Explicitly implement the interface and Implement the interface.
When you derive a class from an interface, intellisense suggest you to do both.
But, what's the difference?
Another aspect of this:
If you implicitly implemented, it means that the interface members are accessible to users of your class without them having to cast it.
If it's explicitly implemented, clients will have to cast your class to the interface before being able to access the members.
Here's an example of an explicit implementation:
interface Animal
{
void EatRoots();
void EatLeaves();
}
interface Animal2
{
void Sleep();
}
class Wombat : Animal, Animal2
{
// Implicit implementation of Animal2
public void Sleep()
{
}
// Explicit implementation of Animal
void Animal.EatRoots()
{
}
void Animal.EatLeaves()
{
}
}
Your client code
Wombat w = new Wombat();
w.Sleep();
w.EatRoots(); // This will cause a compiler error because it's explicitly implemented
((Animal)w).EatRoots(); // This will compile
The IDE gives you the option to do either - it would be unusual to do both. With explicit implementation, the members are not on the (primary) public API; this is handy if the interface isn't directly tied to the intent of the object. For example, the ICustomTypeDescriptor members aren't all that helpful to regular callers - only to some very specific code, so there is no purpose having them on the public API causing mess.
This is also useful if:
there is a conflict between an interface's Foo method and your own type's Foo method, and they mean different things
there is a signature conflict between other interfaces
The typical example of the last point is IEnumerable<T>, which has a GetEnumerator() method at two levels in the interface hierarchy - it is common to implement the typed (IEnumerator<T>) version using implicit implementation, and the untyped (IEnumerator) version using explicit implementation.
Here's the difference in plain English:
Suppose you have an interface Machine, which has a function Run(), and another interface Animal which also has a function called Run(). Of course, when a machine runs, we're talking about it starting up, but when an animal runs, we're talking about it moving around. So what happens when you have an object, lets call it Aibo that is both a Machine and an Animal? (Aibo is a mechanical dog, by the way.) When Aibo runs, does he start up, or does move around? Explicitly implementing an interface lets you make that distinction:
interface Animal
{
void Run();
}
interface Machine
{
void Run();
}
class Aibo : Animal, Machine
{
void Animal.Run()
{
System.Console.WriteLine("Aibo goes for a run.");
}
void Machine.Run()
{
System.Console.WriteLine("Aibo starting up.");
}
}
class Program
{
static void Main(string[] args)
{
Aibo a = new Aibo();
((Machine)a).Run();
((Animal)a).Run();
}
}
The catch here is that I can't simply call a.Run() because both of my implementations of the function are explicitly attached to an interface. That makes sense, because otherwise how would the complier know which one to call? Instead, if I want to call the Run() function on my Aibo directly, I'll have to also implement that function without an explicit interface.
Explicit will put IInterfaceName. at the front of all of the interface implementations. It's useful if you need to implement two interfaces that contain names/signatures that clash.
More info here.
Explicitly implement puts the fully qualified name on the function name consider this code
public interface IamSam
{
int foo();
void bar();
}
public class SamExplicit : IamSam
{
#region IamSam Members
int IamSam.foo()
{
return 0;
}
void IamSam.bar()
{
}
string foo()
{
return "";
}
#endregion
}
public class Sam : IamSam
{
#region IamSam Members
public int foo()
{
return 0;
}
public void bar()
{
}
#endregion
}
IamSam var1;
var1.foo() returns an int.
SamExplicit var2;
var2.foo() returns a string.
(var2 as IamSam).foo() returns an int.
Here you go, directly from MSDN
The difference is that you can inherit a class from several interfaces. These interfaces may have identical Method signatures. An explicit implementation allows you to change your implementation according to which Interface was used to call it.
Explicit interface implementation, where the implementation is hidden unless you explicitly cast, is most useful when the interface is orthogonal to the class functionality. That is to say, behaviorally unrelated .
For example, if your class is Person and the interface is ISerializable, it doesn't make much sense for someone dealing with Person attributes to see something weird called 'GetObjectData' via Intellisense. You might therefore want to explicitly implement the interface.
On the other hand, if your person class happens to implement IAddress, it makes perfect sense to see members like AddressLine1, ZipCode etc on the Person instances directly (implicit implementation).