Can someone explain the exact use of interfaces in C#?
Has msdn not been helpful on this?
http://msdn.microsoft.com/en-us/library/87d83y5b.aspx
This has been discussed so many times here in the past that it is hard to pick any one duplicate for this question.
To save the time of repeating what has been said before, try this search, and start going through the results.
Imagine the the situation of having a factory that creates cars. You know that every vehicle has an engine and can be started, so you have the following:
interface IVehicle
{
Engine vehicleEngine { get; set; }
bool StartEngine();
}
Now, the factory makes an array of other vehicles, so for instance a truck and a normal car:
public Car : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Cars needs to do xyz to start
}
public int MaxNumberOfPassenger { get; set; } // Specific to Car
}
and then:
public Truck : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Trucks needs to do abc to start
}
public int MaximumLoad { get; set; } // Specific to Truck
}
This therefore forces all vehicles to implement specific members to fall under the category of a vehicle, but then can also be specialized with their own distinct members.
In the most simple terms, an Interface expresses what one, or more classes can do, although the implimentation may vary across the various classes.
Polymorphism
You can use 2 classes that implement the same interface without having to know exactly which concrete class it is. It aids in keeping code loosely coupled.
An interface defines the minimum requirements that a class that can be instantiated must implement. It expresses this through methods.
For instance, an interface could define a function called Foo which takes an integer and returns a boolean:
public interface ICanFoo
{
bool Foo(int number);
}
Any class which implements this interface must also implement this method:
public class Fooable : ICanFoo
{
public bool Foo(int number)
{
// do something
}
}
The implementation within the method is up to the specific classes which are implementing the interface.
By using interfaces you no longer care about implementation are compile time, but rather specification. You can call it like this:
ICanFoo myFooable = ...
bool success = fooable.Foo(4);
The actual type of fooable can be any class that implements ICanFoo since you know that ICanFoo will always define a method implementation for the Foo method.
Related
I'm wondering if there is a way to constrain the implementations of a generic type by asking Not to implement a specific interface
Something like
public class PrivateGarage<TVehicle> where TVehicle : **not** Itruck
{
...
}
This might works but it's less elegant
public class PrivateGarage<TVehicle>
{
public PrivateGarage()
{
if(typeof(TVehicle) is Itruck)
{
throw new ArgumentException("Truck is not a valid type for private garage");
}
}
}
There is an approach you can take to solve this, but it only works well if there is only one discriminant to worry about.
Let's suppose the base interface is IVehicle:
public interface IVehicle
{
public void Park();
}
In your case, the discriminant is whether or not the vehicle can go in the garage, i.e., is it a "private vehicle"?
The following two interfaces can represent the discriminant:
public interface ICommercialVehicle: IVehicle
{
}
public interface IPrivateVehicle: IVehicle
{
}
Now you can represent a private garage by requiring IPrivateVehicle rather than IVehicle:
public class PrivateGarage<T> where T: IPrivateVehicle
{
readonly List<IPrivateVehicle> _vehicles = new();
public void Park(T vehicle)
{
_vehicles.Add(vehicle);
}
}
Suppose you also have a Truck type that does not inherit directly or indirectly from IPrivateVehicle. In that case if you try to create a PrivateGarage<Truck> you'll get a compile error.
This approach does not scale at all well, so it's probably better to take the approach of using properties and checking them at runtime.
A slightly different approach is to use interfaces as "Tags". I must stress that this is considered by many to be a bad design.
To do that you'd use an IPrivateVehicle tag as a kind of attribute.
Then the hierarchy would be like this:
public interface IVehicle
{
public void Park();
}
public interface IPrivateVehicle {} // Tag interface. Considered bad design.
public class PrivateGarage<T> where T: IPrivateVehicle, IVehicle
{
readonly List<IVehicle> _vehicles = new();
public void Park(T vehicle)
{
_vehicles.Add(vehicle);
}
}
public interface ICar: IVehicle, IPrivateVehicle
{
}
public interface ITruck : IVehicle
{
}
Then if you had concrete classes implementing ICar and ITruck called Car and Truck respectively:
var carGarage = new PrivateGarage<Car>(); // Compiles
var truckGarage = new PrivateGarage<Truck>(); // Does not compile.
An advantage of this approach is that you can use many tags.
An disadvantage of this approach is that you can use many tags. ;)
No, there isn't. The only way to specify constraints is inclusive. There is no way to exclude specific subtypes. See the documentation for the list of permitted types of constraints.
The reason, most likely, is such a constraint would break polymorphism. If it were possible, it would mean that instances of a specific descendant of the actual type parameter, and its all descendants would, could not be passed to the generic class.
A possible alternate way to impose such a constraint is to introduce properties at an IVehicle interface such as:
public interface IVehicle
{
bool CanCarryPassengers { get; }
bool CanCarryCargo { get; }
}
However, there's much more to check for a hypothetical PrivateGarage, so in the reality, the conditional to allow a particular vehicle in the garage would be much more complicated than a simple negative constraint.
No, there is no weay to exclude a type, constraints don't work that way.
A common solution would be to have an interface specifically for this, like IVehicleThatCanGoInGarage, which may itself also implement IVehicle
public interface IVehicleThatCanGoInGarage : IVehicle
{}
public class PrivateGarage<TVehicle> where TVehicle : IVehicleThatCanGoInGarage
{
...
}
So say I have a class
public abstract class Mammal { ... }
public class Wolf : Mammal
{
// concrete methods and
}
But I don't want to do something like:
List<Wolf> myWolfPack = new List<Wolf>();
I sort of want to say:
WolfPack myWolfPack = new WolfPack();
Which means I basically need to write a WolfPack class:
****public class WolfPack : IList<Wolf>
{
// properties, methods that implements IList
// WolfPack-specific methods
}****
The reason I want to do this is because I wolf packs have specific properties (e.g. a leader, an omega).
WolfPack-specific methods
Wolf Leader { get;set; }
Wolf Omega { get;set; }
So here are my newbie questions:
What is this called? Is there a name for wanting to add methods to a collection/list/existing concrete object? If I'm just using a private List inside my WolfPack class, should I instead just say: public class WolfPack : List
? Seems weird to do this with a concrete class, no? Are there any downsides to this?
Sorry if my words are weird.
I suggest you use composition instead of inheritance. Something like this:
public class WolfPack
{
public IReadOnlyList<Wolf> Members { get; private set; }
public Wolf Leader { get; private set; }
public Wolf Omega { get; private set; }
}
Any operations specific to a WolfPack collection of Wolf should be methods on the WolfPack class. This does not require any modification to the .NET collection class used internally.
Encapsulation is probably what you're looking for. However, to answer
Is there a name for wanting to add methods to a collection/list/existing concrete object?
directly, you probably want extension methods.
I would argue that WolfPack may seem, at first glance, to be an IList<Wolf>, but are you sure that a WolfPack must expose every member that IList<> will require? Chances are, it won't. You probably want to use a List<Wolf> inside your WolfPack implementation as a private field.
You don't have to inherit from the collection class. There are reasons why inheritance is considered problematic - Prefer composition over inheritance?
Instead, your could pack class can be composed of items:
public class WolfPack {
// composed of items
private List<Wolf> _wolves = new List<Wolf>();
// lets you add items
public void Add( Wolf wolf ) {
this._wolves.Add( wolf );
}
public IEnumerable<Wolf>() {
return this._wolves;
}
public Wolf Omega { get; set; }
...
This way you hide the way pack is composed of items and, in future, you could even completely change the implementation (to use another type of list or to change the way wolves are added to the pack for example) with/without changing the interface. On the other hand, inheriting from List would determine the class interface and would not let you change/remove specific methods/properties.
I should start by saying that I am very much a noobie with interfaces so this might be a really dumb question. Also apologies if my Title is unclear - matches the state of my mind!
I do understand the principles behind interfaces and I am want to use them here both to support unit testing and also decoupling via a DI Framework in what is horribly messy and un-testable legacy code.
I have an inteface called IDatHandler. It has a List<> property called Items. The concrete implementations should return a concrete type of IDatContainer. There are some methods of course but I have left them out
public interface IDatHandler
{
....
List<IDatContainer> Items
{
get; set;
}
}
This is a concrete implementation:
public class ADEColorHandler : IDatHandler
{
....
public List<ADEColor> Items
{
get; set;
}
}
}
ADEColor implements IDatContainer. The concrete implementation fails unless I replace ADEColor with IDatContainer.
Is there a way to get Items returned as a list of type ADEColor or am I just breaking the rules?
I should have said that this app is currently using NET 3.5
=========>>> The Answer - thanks Charleh!
The IDatHandler Interface
public interface IDatHandler<T> where T : IDatContainer
{
....
List<IDatContainer> Items
{
get; set;
}
}
The concrete Class:
public class ADEColorHandler : IDatHandler<ADEColor>
{
....
public List<ADEColor> Items
{
get; set;
}
}
}
My units tests on ADEColorHandler Assert against this list and pass.
You could go this route:
public interface IDatHandler
{
// Any common interface stuff
}
public interface IDatHandler<T> : IDatHandler
where T : IDatContainer
{
// Any generics
List<T> Items;
}
public class ADEColorHandler : IDatHandler<ADEColor>
{
....
public List<ADEColor> Items
{
get; set;
}
}
This does mean you need to do some casting at the other end though since if you just pass around IDatHandler instances, you need to know the generic type before you can query Items
What are you trying to achieve? That might help determine what you can use...
Alternatively you could use IEnumerable in your original interface implementation - do you need to know the concrete type of the collection at design time or can you get away with casting?
Edit: added the constraint above
Just trying to get my head round this because using the above interface will work to a certain degree but my assumption is that you want to loop through these to process them etc - I'm wondering if this would work (need to check)
List<IDatHandler<IDatContainer>> someList = new List<IDatHandler<IDatContainer>>();
someList.Add((IDatHandler<IDatContainer>)new ADEColorHandler());
Then you could enumerate the list... going to just check to see if this works.
Edit: nope, didn't work since the generic type is actually different at runtime. I'll have a mess around - I enjoy trying to work out what you can and can't do with generics!
Edit:
Ok so the best one is probably:
public interface IDatHandler<T> : IDatHandler
where T : IDatContainer
{
List<T> Items { get; set; }
}
public class ADEColorHandler : IDatHandler<IDatContainer>
{
public List<IDatContainer> Items
{
get;
set;
}
}
Which means you can do:
var items = new List<IDatHandler<IDatContainer>>();
items.Add(new ADEColorHandler());
then you can enumerate and get Items from each IDatHandler and query each IDatContainer. Of course you are hidden from the concrete types but I assume you have an interface on the containers to try and abstract those implementation details. This should be fine
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.
Here's the simplest form of my question:
IApple requires, among other things, property Flavor
IToffeeApple also requires property Flavor
The problem is, I want IToffeeApple to implement IApple (public interface IToffeeApple : IApple), but they both have the same property requirement. This becomes a problem when, for 1 purpose I need a Collection of Sweets (only IToffeeApple) where IToffeeApple can also be recognised as IApple.
Is it ok to use the "new" keyword in my interface, so that any implementers have 2 Flavor properties?
Have I explained myself poorly? :\
edit: I have. The actual context is geometry:
ILine requires a Start and End point IPoint.
ICurve requires a Start and End point IControlPoint.
ICurve is just extra functionality on top of ILine, yet it means I want to return the Start and End as IControlPoint rather than IPoint, so I either implement both and have a return of both IControPoint and IPoint of Start and End, or I just ignore IPoint/ILine and throw DRY out the window.
This is an elaboration of David Culp's answer. It's quite long, so I'm not posting as a comment.
While the generic interface IList<TPoint> looks like a good solution, I would recommend to elaborate the semantics a bit further. Also, it's advisory to consider introducing both generic and non-generic versions of some interface (like IEnumerable plus IEnumerable<T>).
In your clarified example you should introduce a term describing a finite entity that has a starting and ending point. Generally a curve is not a line but a line is a curve. However, since your curve uses ControlPoints to describe its start and end, while the line uses plain Points instead, in your specific case a line is not a curve. Instead, both line and curve are something like a shape.
// this interface will denote any shape that has a starting and ending point
public interface IShape
{
IPoint Start { get; set; }
IPoint End { get; set; }
}
// this interface will allow for specialization of staring end ending points' type
public interface IShape<TPoint> : IShape
{
// note 'new' will be required here most probably, I didn't compile it
TPoint Start { get; set; }
TPoint End { get; set; }
}
// a line will be a shape descibed by a pair of points; for the sake of
public interface ILine : IShape<Point> { }
// a curve will be a shape described by a pair of control points
public interface ICurve : IShape<ControlPoint> { }
Then, the actual implementations of ILine and ICurve can use explicit implementations of the Start and End properties coming from the non-generic IShape interface. This will favor strongly-typed access to the delimiting points, while preserving the ability to work with them as with plain IShapes.
public class Curve : ICurve
{
public ControlPoint Start { get; set; }
public ControlPoint End { get; set; }
IShape.Start
{
get { return Start; }
set
{
if (!(value is ControlPoint)) ... some error handling ...;
Start = (ControlPoint)value;
}
}
IShape.End { ... similarly as IShape.Start ... }
}
public class Line : ILine { ... similarly as Curve ... }
Note that in respect to the possible error scenario shown above an improvement could be limiting IShapes properties to getters only. Or, the setter passing the value into the strongly-typed version of Start or End could do some kind of conversion of a point into a control point. The right solution is domain-specific of course.
Try something along the lines of:
interface IFlavor;
interface ISweets: IFlavor;
interface IApple: IFlavor;
interface IToffeeApple: IApple, ISweets;
IEnumerable<ISweets> can hold the IToffeeApple, but not IApple.
When there seems to be a need to 'replace' an inherited property for the inheritance make sense I generally look for one of two things. Either the inheritance is forced (a car and an apple both have a color, but are not often thought of as polymorphic), or the inheritance is deeper than it seemed at first glance.
If I understand the example well enough, deeper inheritance fits well enough.
To fit your new example:
public interface IPoint
{}
public interface IControlPoint : IPoint
{
// added functionality of IControlPoint
}
public interface ILine<TPoint>
where TPoint : IPoint
{
TPoint Start { get; set; }
TPoint End { get; set; }
}
public interface ICurve<TPoint> : ILine<TPoint>
where TPoint : IPoint
{
// added functionality of ICurve
}
I am making the assumption that IControlPoint implements IPoint, but it seemed reasonable.
Basically, generics takes care of ICurve needing an IControlPoint to work with, while ILine needs an IPoint.
No, you don’t need the new keyword to inherit a property from an interface in another interface:
public interface IApple
{
Flavor Flavor { get; }
}
public interface IToffeeApple : IApple
{
ICollection<Sweet> Sweets { get; }
}
public class MyToffeeApple : IToffeeApple
{
public Flavor Flavor { get { return Flavors.ToffeeFlavor; } }
public ICollection<Sweet> Sweets { get { return new Sweet[0]; } }
}
Works just fine. If this doesn’t answer your question, please edit the question to include detail that explains in what way the above is insufficient.
No, because IToffeeApple is only inheriting from IApple (it isn't implementing anything, it's an interface) and there's no conflict; just leave the Flavour property out so it inherits it from IApple.
This doesn't becomes a property with a collection that only has IToffeeApple, because there won't be any conflicting cases there either.
It could only really become a problem if something implemented both IToffeeApple, and either something else where flavour had a different type, or IQuark where flavour has a different meaning. In this case the class implementing them should implement on or both of the properties explicitly.