I have some interfaces that need some simple implementation, but I have a handful of them, like for instance (not actual code, just example)
interface ISelectable
{
public bool IsSelected;
public void Select();
}
public class Selectable : ISelectable
{
public bool IsSelected {get;set}
public void Select()=> IsSelected = true;
}
Then I might have IStorable, which allows storing stuff in the database, like:
public interface IStorable
{
public void Store();
...
}
public class Storable : IStorable
{
private stuff...
public void Store() { storing code }
}
The question is:
I have
elements that are IStorable but not ISelectable,
elements that are ISelectable and no IStorable,
and elements that are both.
Actually... I have MORE of these classes. So the combinations grow fast.
As far as I know, the only way to share the code is to have a base class implement the interface, then your class inherits from this base class. Like:
public class GameCard : Selectable { ....
But this would mean that the only way to have a class that inherits the code for Selectable, and the code for Storable is to have a base class doing both, something like public class StorableAndSelectable: IStorable, ISelectable But this makes no sense, especially when you want to have different storing methods...
What's the proper way to have your classes share the implementation code of the interfaces it implements? Having the implementation for each of them in one file, and feeding this "file" to all classes that need it?
I would consider if inheritance is the correct approach for such simple properties. There are some possible alternatives. Using inheritance to include functionality is called implemention inheritance and is generally frowned upon. For simple stuff like this it provides little benefit, and for more complicated logic it ties the derived class to the base class to tightly.
To store an object I would probably suggest the repository pattern, that way you do not need a special interface.
To handle things like if a object is selected, the easiest option is probably just to have a settable property in the interface: bool IsSelected {get;set;}. This is trivially implementable by all derived classes, there is no real advantage of a implementation of just that interface, at least not outside of testing/dummy objects.
In some cases you can use a Func<T, bool> to describe how to determine if some arbitrary type is selected. In some cases it might be useful to use composition, i.e. use a separate class to describe selection, and have your game objects contain a property of this class.
Starting from C# 8.0 you can have default method implementation in interface definition
interface IA
{
void M() { WriteLine("IA.M"); }
}
class C : IA { } // OK
IA i = new C();
i.M(); // prints "IA.M"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
According to your classes you can do something like this
interface ISelectable
{
public bool IsSelected;
public void Select() => IsSelected = true;
}
Related
My understanding of inheritance is pretty basic.
I want to create a base class, which implements IDisposable and then let other classes with functionality inherit from that base class, so that they share a base type.
It would allow me to put every object into one list, so that I can dispose of everything in one go, when I want to clean up.
The thing is, a class in C# can only inherit once and otherwise only use interfaces.
Now, how can classes like Thread, inherit from my base class without me having to basically code the Thread class all over again?
It may sound dumb, but in short: I want to let already existing classes inherit a base class of my choosing without loosing its functionality. (So that all classes used in a project have a common base, to be summed up into one object type, for like List)
Is that even possible?
If your aim is to simply store a list of objects which can be disposed, then you want a List<IDisposable>. Any class which, directly or indirectly implements that interface can be stored therein.
var disposables = new List<IDisposable>();
disposables.Add(new MyClass1());
disposables.Add(new SomeClass());
disposables.Add(new AnotherClass());
disposables.ForEach(d => d.Dispose());
Whether this is a worthwhle pattern, I'm not convinced!
Example you given invlolves interface IDisposable. In C#, class can implement multiple interfaces.
On the other hand, in C# class may inherit from exactly one class.
Having said that, it is not always good idea to inherit from classes, as it very limiting. Instead I would suggest composition: wiki
For example, I would suggest something like composition design pattern (it is a small variation, as the composite does not have collection of objects, rather just one object):
public interface IFoo
{
void DoFooStuff();
}
public class Foo : IFoo
{
public void DoFooStuff() {...};
}
public class ShouldImplementFoo : IFoo
{
// Composition, you need to initialize it some time
private Foo _foo;
public void DoFooStuff() { _foo.DoFooStuff(); }
}
EDIT
After rethinking your problem, you seem to want to put some set of objects (of different classes) in a list, so you can execute some defined action on each object in a list.
The simpliest is: define interface with your defined action:
public interface IMyIntf
{
void MyDesiredAction();
}
And now, make all classes implement it. Now you might think "Well, now I need to implement this method everywhere..." - nothing like that! Just use adapter design pattern, for example, having class:
public class MyConcreteClass
{
public void ActionIWishToExecuteOnThisObject()
{ ... }
}
you just modify it to:
public class MyConcreteClass : IMyIntf
{
public void ActionIWishToExecuteOnThisObject()
{ ... }
// implement interface
public void MyDesiredAction()
{
ActionIWishToExecuteOnThisObject();
}
}
Now, you can use some aggregate, like List<IMyIntf>, place all objects you are interested in there and do:
foreach(var item in myList)
item.MyDesiredAction();
A class can inherits from an ancestor class (else Object, the root of all).
Also it can implements some interfaces (or none).
A class can have non implemented members as being abstract, so the class is abstract.
Also members can be virtual to enable polymorphism (abstract members are).
Once implemented, a thing is available in the class that can be instantiated for real if not abstract, and is available for all children too, except whose that are private which are hidden in subclass.
There is no need to repeat and that is one of the power of OOP.
Doing so, using abstraction, encapsulation, inheritance and polymorphism, after stuying the real world and the domain where we work, we can design a projection of this real world, a view in our mind, with concepts having data (fields and properties) and operations (methods), classed in artifacts (objects) and things like relations, composition, aggregation, interfaces, components, controls, and so on.
Thus we can factorize processings to not repeat like for example:
Having a Animal class and Cat and Dog child classes,
We put in animal the Size and the Color aspect,
As well as the Eat and Walk methods implemented for all animals,
And an abstract non-implemented DoSound.
Therefore:
In concrete classes Cat and Dog we don't implement again the things,
Except DoSound that is particular for each real animal gender.
Concerning interfaces, they are virtual contracts.
For example we can have animals and buildings that have nothing in common, at first look (we will not go back to atoms and photons), but we want to be able to manage instances of objects like cat and dog, as well as house and museum to take a photo.
To acheive that we define an interface IPhotoTaking and when defining previous classes, we add that they implements this interface.
Code sample:
public interface IPhotoTaking
{
Image TakePhoto();
}
public abstract class Animal : IPhotoTaking
{
public int Size { get; set; }
public Color Color { get; set; }
public void Eat() { ... }
public void Walk() { ... }
public abstract void DoSOund();
public Image TakePhoto();
}
public class Cat : Animal // no need to repeat IPhotoTaking
{
public override void DoSound() { ... }
}
public class Dog : Animal
{
public override void DoSound() { ... }
}
public abstract class Building :IPhotoTaking
{
public Image TakePhoto();
}
public class House : Building
{
}
public class Museum : Building
{
}
Now having this list we can use polymorphism like that:
var animals = new List<Animal>();
foreach ( var animal in animals )
animal.DoSound();
Also without polymorphism and because C# does not support true polymorphism with the diamond operator yet applied on List<> here, we can use the interface like that:
var items = new List<IPhotoTaking>();
foreach ( var item in items )
item.TakePhoto();
Remark: if taking a photo may be different for each types, we can set it virtual to specialize its implementation in each.
OOP Basic Principles
What is abstraction in C#?
How to choose between public, private and protected access modifier?
Association, Composition and Aggregation
What is polymorphism?
What is the difference between an interface and a class?
About the lack of true generic polymorphism and the missing diamond operator in C#
I have run into this situation many times, and have 'hacked' my way around the situation, but it seems it's a gap in my understanding.
Given the following code:
public class Foo
{
Bar barA = new BarA();
private void Bat() => barA.Baz();
}
public abstract class Bar
{
// Obviously this *can't* be private
private abstract Baz();
}
public class BarA : Bar
{
public void Run() => Baz();
// Again this can't be private
private override Baz() => DoSomething();
}
(caveat: I used expression bodied methods for sake of brevity in the example. Normally I would not unless there was a good reason to.)
Now, in the above example, my logic is that the Baz method needs to be defined by the concrete class, however the reason I want it private (and yes, I understand WHY it can't be, because it would be completely invisible/inaccessible to the concrete class), is logically, I do not want the concrete class to be able to call the method, merely define it.
The way to fix the code is to make the method protected, however, then the method becomes available to executable from within the concrete class.
Ultimately, I want an abstract/base class that handles internals of executing some code that is defined by the concrete class, however never available for the concrete class itself to call/execute. What is the flaw with that logic, or how should I be implementing that logic properly.
** EDIT: A concrete implementation **
Let's say for example this is part of a plugin system within a library (that I am creating, and another developer is implementing). Another part of the library uses derived classes that implement this abstract class (say it's a filter in image processing). The developer define's the method on what the filter does, however the abstract class (essentially handles the only processing that the defined filter provides), and yes the contract (interface) is made for the image processor so it doesn't (need to) know/care about implementation anyhow.
Like I said in the comments, what you're trying to do is a bit of a code smell. If your derived class needs to define how something in the base class works, then consider passing in an interface to the base. That way you're note exposing any public methods you don't need to and making things much more testable. You could do it something like this.
The interface and an implementation:
public interface IBaz
{
void Baz();
}
public class BigBaz : IBaz
{
public void Baz() => Console.WriteLine("Big Baz!");
}
Now your code slightly modified:
public abstract class Bar
{
private readonly IBaz _baz;
public Bar(IBaz baz)
{
_baz = baz;
}
public void DoBaz() => _baz.Baz();
}
public class BarA : Bar
{
//Here I'm passing into the constructor, but you may find it preferable
//to pass the IBaz directly as a parameter of the DoBaz method
public BarA() : base(new BigBaz())
{
}
}
Let's say I have a base class named BaseClass:
public BaseClase{
public bool isCool;
}
Now let's say I have two classes that inherit from BaseClass
public Class1: BaseClass{
public bool isGreen;
}
public Class2: BaseClass{
public bool isPurple;
}
Now let's say I want to create a list that contains instances of both Class1 and Class2 by creating a List;
var genericList = new List<BaseClass>();
Next, let's add an instance of Class1 and Class2 to genericList.
genericList.Add(new Class1());
genericList.Add(new Class2());
Now, here is what I have a question about. If I want to access Class1.IsGreen or Class2.IsPurple, I have to cast each item in genericList as Class1 or Class2.
foreach(var item in genericList){
if(item is Class1){
var temp = (Class1) item;
temp.IsGreen = true;
}
if(item is Class2){
var temp = (Class2) item;
item.IsPurple = true;
}
}
Is this just the way you're supposed to do things? It seems very clunky to me, and the complexity of the code I'm writing that uses this type of code structure is getting out of hand. I'm new to inheritance, and want to learn if this is just the way you're supposed to do things, or if there are better alternatives out there.
It really depends on what you are trying to do. If you can abstract out the property, so something like IsSelected, then you could expose it on your BaseClass as a virtual or abstract property. Then you wouldn't have to cast your items in your for-loop.
Or you could abstract it out to a abstract/virtual method, like UpdateColor(bool). Then each derived class could override that and set the appropriate property on themselves.
There are several other alternatives, including interfaces and extension methods, that you could use to make it cleaner.
There is basically no better alternative, although if you only want to operate on, say Class1's then you can use the OfType extension
var genericList = new List<BaseClass>();
genericList.Add(new Class1());
genericList.Add(new Class2());
foreach(var item in genericList.OfType<Class1>())
{
// no need to cast
item.IsGreen = true;
}
If you can abstarct somehow what are you doing in the cycle, for instance, you are applying a Default colors for an item, so expose method IEntity.SetDefaultColors(IColorInformation) and implement it in each item class.
BTW: Consider the Interface segregation principle and introduce a common interface for you entities like IEntity.
To better (or worse) illustrate, I'm going to change IsGreen to IsSpecial and IsPurple to MaximumHappiness--just so that we can be clear that the two properties represent two very different things.
One way to handle it would be to make them both properties of the base class (if applicable), so then you don't have to typecast them.
Another would be to provide a function to the base class (which the inheriting classes could override). For instance, the function could be called "DoSpecialThing" and inside of it you can access any properties on the child classes.
If the properties are guaranteed to be boolean (and represent some amount of related ideas), then you might be able to use flags. For instance:
[Flags]
enum MoodType
{
//Moods
Happy,
Sad,
Elated,
Overjoyed,
Depressed,
//Mental States
Confused,
Alert,
Sluggish,
//Other
Sleepy,
Awake
}
So now the base class could have a property called "State" or something and it can be any combination of the above flags. So you could indicate that an object is Sleepy, Confused, and Happy all in one property.
You can read more about flags (and decide if they're applicable to your situation) at this link.
I'd recommend this SO question, too. Specifically the top-voted (although unaccepted) answer.
I would say somethign like this, pseudoecode!:
public abstract BaseClase{
public bool isCool;
public abstract setColor();
}
public Class1: BaseClass{
public bool isGreen;
public override void SetColor() {IsGreen=true;}
}
public Class2: BaseClass{
public bool isPurple;
public override void SetColor() {IsPurple =true;}
}
foreach(var item in genericList){
item.SetColor();
}
Should work..
Regards.
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.