I've found a behaviour in c# and I would like to know if it's in the specs (and can be expected to work on all platforms and new versions of the .NET runtime) or if it's undefined behaviour that just happens to work but may stop compiling at any time.
So, let's say I want to take existing classes, like these:
public class HtmlTextBox
{
public string Text {get; set;}
}
public class HtmlDiv
{
public string Text {get; set;}
}
now I would really like them to implement a common IText interface, like this one:
public interface IText
{
string Text {get; }
}
but I can't change the classes directly because they are part of an external library. Now there are various ways to do this, through inheritance or with a decorator.
But I was surprised to find out that doing simply this compiles and works on .NET 4.5 (windows 7 64 bits).
public class HtmlTextBox2 : HtmlTextBox, IText {}
public class HtmlDiv2 : HtmlDiv, IText {}
That's it. This gets me drop-in replacements for HtmlTextBox and HtmlDiv that use their existing Text property as implementation for IText.
I was half-expecting the compiler to yell at me, asking me to provide an explicit re-implementation of Text, but on .NET 4.5 this just works:
IText h2 = new HtmlTextBox2{Text="Hello World"};
Console.WriteLine(h2.Text); //OUTPUT: hello world
In fact,I've tried the same on mono (whatever version ideone.com is using) and mono does not yell at me either
So I guess I'm good to go, but before trying this on serious code I wanted to check if I've misunderstood what is really happening here or if I can't rely on this to work.
Yes, this is expected behavior. The implementation of an interface's method needs not to be done in the class where the interface is actually applied; it can be in any ancestor class.
The C# Language Specification 5.0 documents this in section 13.4.4; excerpt of the rule:
The implementation of a particular interface member I.M, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located
Some clarification to my comment
Yes, that should indeed just work as intended. An interface defines what methods a class should implement (either directly or throughout the hierarchy).
When you define an interface, you could look at it like this:
An interface's only task is to guarantee that at any point in a class' hierarchy where the interface is defined in the signature, that class has every method in the interface implemented.
Here's a sample situation that hopefully sheds some light:
void Main()
{
Z obj1 = new C();
Z obj2 = new B();
Z obj3 = new A();
Y obj4 = new C();
Y obj5 = new D();
Z obj6 = new D();
}
interface Y {
void someMethod1();
void someMethod2();
}
interface Z {
void someMethod3();
}
class A : Z {
public void someMethod3() { }
}
class B : A {
public void someMethod1() { }
}
class C : B, Y {
public void someMethod2() { }
}
class D : C { }
This compiles just fine.
As you can see, B implements Y's method someMethod1 after which C extends B and implements Y. All C does is provide an implementation for someMethod2 and at that point the interface definition is reached: the two methods that are defined in Y are now available to an object of type C.
What's key here is to remember that a class hierarchy are just layers with, amongst others, some methods. At the moment in a hierarchy where you say "this class needs to implement every method defined in <SomeInterface>" you basically have to make sure that each of them is available to your class at that point. Inheritance tells us that we can use the methods of a superclass, which means that by implementing your method in a baseclass you have satisfied the condition.
Sidenote: all of this is written without abstract methods in mind, they're a little different.
Related
In my interface, I have declared a property with setter and getter.
public interface ITestInterface
{
string AProperty { get; set; }
}
When I code my class which inherit that interface, why I need to define these two properties again?
public sealed class MyClass: ITestInterface
{
public string AProperty { get; set; }
}
Because you are not inheriting from an interface, you are implementing the interface. (although they both share same syntax :)
public class MyClass : IMyInterface { ... } //interface implementing
public class MyClass : MyBaseClass { ... } //inheriting from a class
Assume you are inheriting a candy box (not from your ancestors, in programming manner), it is something (not exactly) like you put the candy box in another box, now the outer box (the derived class, the inherited one) is inherited from candy box and have all the things candy box have, but if you want to implement (make) a candy box yourself you must build a box and put some candy in it. This is the way interfaces work.
Your interface definition only tells there is a property with a getter and setter, not how it is implemented. You could use auto-implemented properties, but you are not required to.
Following the interface, this would be a valid implementation:
public sealed class MyClass: ITestInterface
{
public string APROPERTY
{
get { return someField + " hello"; }
set { someOtherField = value; }
}
}
In an interface definition, string AProperty { get; set; } is the declaration of the property, while in a class, it means that the property is auto-implemented.
Short answer
Because interfaces contain no more than a definition of a class, and cannot contain the actual implementation of any member functions. It's by design.
Long answer
First you have to realize that properties are basically get and set member functions with some simplified syntax. The question here is therefore: why can't an interface definition contain an implementation of a member function?
Well, in some languages (most notably: C++) you can.
If you have an inheritance chain, that's basically solved through lookup tables. Say that you have member function 1, then in all the classes in the inheritance chain, there's a table which contains a pointer to function 1. Once you call a member function, the call basically grabs the first entry from the table belonging to the type of your object, and calls that. This thing is called a vtable (and for more details, see here).
Now, in C++, VTables are very transparent to the developer: each class basically has a vtable and there's no such thing as a real 'interface'. This also means that all classes can have implementations and members such as fields. If you have a class with only pure virtual members (e.g. functions without an implementation), you have the C++ equivalent of an 'interface'.
In software engineering, these classes were often called 'interface' classes, because they contain only a definition of what's going on, not the actual implementation. Interfaces have the nice property that they describe functionality without actually going into the details, thereby giving the possibility to put 'boundaries' in your code. There are a lot of use cases for this, including (RPC) communication, a lot of design patterns, and so on.
In C++, a class can derive from multiple classes (multiple inheritance) with and without an implementation. Also, because interfaces are in fact more like 'abstract' classes than like 'interfaces' in C#, this means you can also add functionality there. The vtable that was previously described therefore contains pointers to functions in all the base classes.
The problems with this start when you're starting to add functionality to interface classes. For starters, let's say you have something like this (I'll do this in sort-of C#):
interface A { Foo(); } // basically an interface.
interface B : A { Foo(); } // another interface
class B : A { void Foo() {...} } // implementation of Foo, inherits A
class D : B,C { } // inherits both B, C (and A via both B and C).
What we're interested in here is what happens if you call Foo in class D. For that, we have to construct a vtable for class D. Basically this vtable would look like this:
Foo() -> C::Foo()
This means that if you construct an object of D, and call Foo, you'll end up calling the implementation of Foo in type C:
var tmp = new D();
tmp.Foo(); // calls C::Foo()
It becomes more difficult when we're changing the definition of B into something like this:
class B : A { void Foo() {...} } // changed into an implementation
Again, we try to construct the vtable for class D and we end up with a problem:
Foo() -> C::Foo() or B::Foo()???
The problem we're facing here is: what implementation of Foo are we going to use when calling that member? Also, what constructor are we going to call? And what about destruction order? In C++ there are workarounds for this called virtual inheritance.
While designing .NET and the C# language, they thought about past experiences with multiple inheritance and the implications of virtual inheritance and decided that it's not only a difficult thing to implement, but also very confusing for developers at best. As you've seen, these problems don't exist when you just add interfaces.
So, that's why you cannot have a property (or a method) in your interface.
I think the problem here is, that the same syntax has two different meanings for interfaces and classes. AProperty { get; set; } is in an interface is the declaration-only, in a class it's an automatically implemented interface.
So that term is dependent on the context.
public interface ITestInterface
{
string AProperty { get; set; }
}
Declares the Property, but cannot implement it.
public sealed class MyClass: ITestInterface
{
public string AProperty { get; set; }
}
Implements the interface, where the property is automatically implemented (which only works for classes).
Interface contain property signatures not the actual definitions. You are actually requesting for any class implementing ITestInterface to implement get and set for AProperty. See this and this for more details.
As others say interface is just a container for your methods and properties signatures. It needs implementation but this implementation signature will be perfectly match with one that is used in interface. Also it guarantees that all of this members can be accessed in a class instance as they are by default public properties and without implementation program will not compile at all.
Let's say you have interface:
public interface ITestInterface
{
string AProperty { get; }
}
and class that implements it:
class MyClass : ITestInterface
{
public string AProperty { get { if (DateTime.Today.Day > 7) return "First week of month has past"; return "First week of month is on"; } }
}
It's not possible to use auto-implemented properties and not possible to add setter in this class because interface property lacks set accessor and auto-implemented properties requires that interface contains auto-implemented properties signature ({ get; set;}). So in your example interface just declares properties and that's it.
Just by knowing what interfaces class has inherited you know what members are there and if you just want to use (or allow user to use) some of this methods (not allowing to change anything though) you can always upcast your class instance to one of these interface types and pass it as a parameter.
I think the confusion here comes from the fact that auto properties (just the get and or set declarations) look the same in the interface and the implementation. The interface is merely a declaration (contract) of what a class must provide in order to be deemed an implementer of the interface. It is much clearer if you consider a method declaration in an interface vs its implementation in a class.
Interface = requirements;
Class = how those requirements are fulfilled
public interface ITestInterface
{
string GetAProperty();
}
public class MyClass : ITestInterface
{
public string GetAProperty()
{
// Do work...
return "Value";
}
}
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#
Suppose I have the following class hierarchy:
Class A {...}
Class B : A {...}
Class C : A {...}
What I currently have is
Class D<T> where T : A {...}
but I'd like something of the form
Class D<T> where T in {B,C}
This is due to some odd behavior I'm not responsible for where B and C have common methods which aren't in A, but it would be nice to be able to call them in D on T.
Note: I don't have access to A,B or C to edit them
You need to define an interface for the common methods that are in B and C (lets call it Ibc), make B and C implement this interface, and then you can write:
Class D<T> where T : A, Ibc {...}
This isn't directly possible.
As others suggest, you could define an interface and implement it in both B and C.
If this isn't an option (e.g., if these classes are beyond your control), what I might suggest is this: first, start with an abstract class that includes all the functionality you can achieve with any T deriving from A. Then say you have some methods that exist for both B and C that aren't a part of A. In D you can make these abstract methods to be implemented by subclasses:
public abstract class D<T> where T : A
{
protected T _member;
public void DoSomethingAllTsCanDo()
{
_member.DoSomething();
}
public abstract void DoSomethingOnlyBAndCCanDo();
}
Then you can inherit from the base class for each type B and C and override the abstract method(s) to provide the appropriate functionality:
public class DB : D<B>
{
public override void DoSomethingOnlyBAndCCanDo()
{
_member.DoSomethingOnlyBCanDo();
}
}
public class DC : D<C>
{
public override void DoSomethingOnlyBAndCCanDo()
{
_member.DoSomethingOnlyCCanDo();
}
}
First, If B and C have common methods, it is a design flaw they don't share an interface. That said, you can fix that even without having access to B and C.
It is possible to create a common interface. Suppose you have:
public class A
{
}
public class B : A
{
public void Start() { }
}
public class C : A
{
public void Start() { }
}
You can create a common interface:
public interface IStartable
{
void Start();
}
And use it on derived classes from B and C:
public class BetterB : B, IStartable
{
}
public class BetterC : C, IStartable
{
}
You may not be able to achieve that if you get B and C instances as is, but it can be considered if you create them. In fact, with specialized classes of B and C, you may use the interface instead of D<T>.
Do B and C implement the same interface? That may be a better route.
Some options:
Make an interface IderivedFromA that contain the common methods from B and C.
Looks like this is impossible from your question
In D cast T to dynamic and call the methods dynamically
The most easy solution, if you can use .Net 4
In D test if the you deal with an B or C, cast, and call
Will be checked by the compiler, and is possible from .Net 2
The Dan Tao answer: Create a specific implementation of D<T> for B and C, these can call the methods from B and C directly. (Didn't think of this one myself).
Will only work if the "user-source" knows it is dealing with B or C, and does not use the abstract A to use D<A>. Instead it should use DB or DC. But I think this is the case, otherwise you didn't need generics.
The where constrain in C# does not allow you to specify multiple classes as a choice.
Also if you will specify multiple where contains, then they both has to be satisfied. There is no OR logic for constrain.
Here is specification: http://msdn.microsoft.com/en-us/library/bb384067.aspx
Answers from Grzenio seems right for you. Extract common behavior into the common interface for B and C. Then you can use that interface as a constrain.
Since you don't have access to the source, the only real answer (unless you are willing to lose safety by using dynamic) is explicitly check for B/C and cast.
Yesterday 2 of the guys on our team came to me with an uncommon problem. We are using a third-party component in one of our winforms applications. All the code has already been written against it. They then wanted to incorporate another third-party component, by the same vender, into our application. To their delight they found that the second component had the exact same public members as the first. But to their dismay, the 2 components have completely separate inheritance hierarchies, and implement no common interfaces. Makes you wonder... Well, makes me wonder.
An example of the problem:
Incompatible Types http://www.freeimagehosting.net/uploads/f9f6b862f1.png
public class ThirdPartyClass1
{
public string Name
{
get
{
return "ThirdPartyClass1";
}
}
public void DoThirdPartyStuff ()
{
Console.WriteLine ("ThirdPartyClass1 is doing its thing.");
}
}
public class ThirdPartyClass2
{
public string Name
{
get
{
return "ThirdPartyClass2";
}
}
public void DoThirdPartyStuff ()
{
Console.WriteLine ("ThirdPartyClass2 is doing its thing.");
}
}
Gladly they felt copying and pasting the code they wrote for the first component was not the correct answer. So they were thinking of assigning the component instant into an object reference and then modifying the code to do conditional casts after checking what type it was. But that is arguably even uglier than the copy and paste approach.
So they then asked me if I can write some reflection code to access the properties and call the methods off the two different object types since we know what they are, and they are exactly the same. But my first thought was that there goes the elegance. I figure there has to be a better, graceful solution to this problem.
My first question was, are the 2 third-party component classes sealed? They were not. At least we have that.
So, since they are not sealed, the problem is solvable in the following way:
Extract a common interface out of the coinciding members of the 2 third-party classes. I called it Icommon.
public interface ICommon
{
string Name
{
get;
}
void DoThirdPartyStuff ();
}
Then create 2 new classes; DerivedClass1 and DerivedClass2 that inherit from ThirdPartyClass1 and ThirdPartyClass2 respectively. These 2 new classes both implement the ICommon interface, but are otherwise completely empty.
public class DerivedClass1
: ThirdPartyClass1, ICommon
{
}
public class DerivedClass2
: ThirdPartyClass2, ICommon
{
}
Now, even though the derived classes are empty, the interface is satisfied by the base classes, which is where we extracted the interface from in the first place.
The resulting class diagram looks like this.
alt text http://www.freeimagehosting.net/uploads/988cadf318.png
So now, instead of what we previously had:
ThirdPartyClass1 c1 = new ThirdPartyClass1 ();
c1. DoThirdPartyStuff ();
We can now do:
ICommon common = new DerivedClass1 ();
common. DoThirdPartyStuff ();
And the same can be done with DerivedClass2.
The result is that all our existing code that referenced an instance of ThirdPartyClass1 can be left as is, by just swapping out the ThirdPartyClass1 reference for a ICommon reference. The ICommon reference could then be given an instance of DerivedClass1 or DerivedClass2, which of course in turn inherits from ThirdPartyClass1 and ThirdPartyClass2 respectively. And all just works.
I do not know if there is a specific name for this, but to me it looks like a variant of the adaptor pattern.
Perhaps we could have solve the problem with the dynamic types in C# 4.0, but that would have not had the benefit of compile-time checking.
I would be very interested to know if anybody else has another elegant way of solving this problem.
If you're using .Net 4 you can avoid having to do alot of this as the dynamic type can help with what you want. However if using .Net 2+ there is another (different way) of achieving this:
You can use a duck typing library like the one from Deft Flux to treat your third party classes as if they implemented an interface.
For example:
public interface ICommonInterface
{
string Name { get; }
void DoThirdPartyStuff();
}
//...in your code:
ThirdPartyClass1 classWeWishHadInterface = new ThirdPartyClass1()
ICommonInterface classWrappedAsInterface = DuckTyping.Cast<ICommonInterface>(classWeWishHadInterface);
classWrappedAsInterface.DoThirdPartyStuff();
This avoids having to build derived wrapper classes manually for all those classes - and will work as long as the class has the same members as the interface
What about some wrappers?
public class ThirdPartyClass1 {
public string Name {
get {
return "ThirdPartyClass1";
}
}
public void DoThirdPartyStuff() {
Console.WriteLine("ThirdPartyClass1 is doing its thing.");
}
}
public interface IThirdPartyClassWrapper {
public string Name { get; }
public void DoThirdPartyStuff();
}
public class ThirdPartyClassWrapper1 : IThirdPartyClassWrapper {
ThirdPartyClass1 _thirdParty;
public string Name {
get { return _thirdParty.Name; }
}
public void DoThirdPartyStuff() {
_thirdParty.DoThirdPartyStuff();
}
}
...and the same for ThirdPartyClass2, then you use the wrapper interface in all your methods.
Add an interface. You could add one wrapper (that implements the interface) for each of the 3rd parties.
Anyway, if you have the code of those 3rd parties, you could skip the wrapper thing and directly implement the interface. I'm quite sure you don't have the source, though.
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.