I created a class called MostRecentStack<T> which is a stack that only keeps a certain number of items, dropping the ones at the bottom to make room for new ones. I'd like to have a variable that can store a reference to either a regular ("infinite") stack, or one of my custom type, depending on the circumstances, but C# defines no generic "stack" interface. Normally this wouldn't be a problem, but I'd like System.Collections.Generic.Stack<T> to implement the interface as well.
As long as a class provides the required members, is there any way to, in the interface definition, tell the compiler to consider a class as implementing the interface? I'd like to be able to do this without having to use as or other methods of typecasting.
The exact thing you're asking for isn't possible. However, something like should be very similar to what you want:
public class CompatibleStack<T> : System.Collections.Generic.Stack<T>, IYourStackInterface<T>
{
}
The CompatibleStack is functionally equivalent to System.Collections.Generic.Stack, except it now implements IYourStackInterface.
As long as System.Collections.Generic.Stack has all the right members to implement IYourStackInterface, this should compile fine. And you can pass a CompatibleStack around as an IYourStackInterface without any problems.
No, it is not possible to add new interface to existing class that you don't own. Options:
if you get instance of the class via some dependency injection controller you may be able to wrap class with proxy that will implement interface by calling matching methods.
you can simply derive from existing class and add interface (if it is not sealed) and start using your class.
in your particular case as Baldrick pointed out you can do reverse - derive from existing class and implement interface.
you can try to use dynamic to get some duck typing (as both classes will have matching methods) for some performance, readability and strong type cost.
Side note: in general C# does not support duck typing, but there is one case (foreach) where implementing interface is not strictly required - just having correct methods on collection is enough to support foreach.
Related
In order to maintain binary backwards compatibility in .NET, you generally can't add new abstract methods to public classes and interfaces. If you do, then code built against the old version of the assembly that extends/implements your class/interface will fail at runtime because it fails to fully extend/implement the new version. For classes, however, there is a handy workaround:
public abstract class Foo {
internal Foo() { }
}
Because Foo's constructor is internal, no-one outside of my assembly can extend Foo. Thus, I can add new abstract methods to Foo without worrying about backward compatibility since I know that no class in another assembly can extend Foo.
My question is, is there a similar trick for interfaces? Can I create a public interface and somehow guarantee that no one outside of my assembly will be able to create an implementation of it?
No, you can't do that. But then, considering that the point of an interface is to define the behavior of an implementation by defining a contract, that makes sense.
What you can do, however, is create an internal interface that inherits from your public interface:
public interface IPublicInterface {
/* set-in-stone method definitions here */
}
internal interface IChildInterface : IPublicInterface {
/* add away! */
}
This should prevent any backwards compatibility issues with other assemblies while still allowing you to hide additional methods.
The downside, of course, is that you would have to remember to cast as IChildInterface when you need those, rather than simply being able to use it as an IPublicInterface
In all honesty, though, if you really wanted to define some assembly-only functionality while still requiring that the end user define their own implementations for some methods, then your best bet is probably an abstract class.
No, you can't.
But since in IL an interface is essentially just a pure abstract class (i.e. one without any implementation at all), you can use the technique you've already described and it will be practically the same.
As noted, keep in mind that this approach does restrict your type to inheriting just the fake "abstract class" interface. It can implement other interfaces, but won't be able to inherit any other type. This may or may not be a problem, depending on the scenario.
If it makes you feel better about the design, name your pure abstract class following the .NET convention for interfaces. E.g. IFoo instead of Foo.
Of course, it does imply the question: why do you want to do this? If you have no implementation at all, what harm could come from allowing other code to implement your interface?
But from a practical point of view, it's possible to enforce your rules the way you want.
I've been looking into empty interfaces and abstract classes and from what I have read, they are generally bad practice. I intend to use them as the foundation for a small search application that I am writing. I would write the initial search provider and others would be allowed to create their own providers as well. My code's intent is enforce relationships between the classes for anyone who would like to implement them.
Can someone chime in and describe if and why this is still a bad practice and what, if any alternatives are available.
namespace Api.SearchProviders
{
public abstract class ListingSeachResult
{
public abstract string GetResultsAsJSON();
}
public abstract class SearchParameters
{
}
public interface IListingSearchProvider
{
ListingSeachResult SearchListings(SearchParameters p);
}
}
Empty classes and interfaces are generally only "usably useful" as generic constraints; the types are not usable by themselves, and generic constraints are generally the only context in which one may use them in conjunction with something else useful. For example, if IMagicThing encapsulates some values, some implementations are mutable, and some aren't, a method which wants to record the values associated with an IMagicThing might be written something like:
void RecordValues<T>(T it) where T:IImagicThing,IIsImmutable {...}
where IIsImmutable is an empty interface whose contract says that any class which implements it and reports some value for any property must forevermore report the same value for that property. A method written as indicated could know that its parameter was contractually obligated to behave as an immutable implementation of IMagicThing.
Conceptually, if various implementations of an interface will make different promises regarding their behaviors, being able to combine those promises with constraints would seem helpful. Unfortunately, there's a rather nasty limitation with this approach: it won't be possible to pass an object to the above method unless one knows a particular type which satisfies all of the constraints, and from which object derives. If there were only one constraint, one could cast the object to that type, but that won't work if there are two or more.
Because of the above difficulty when using constrained generics, it's better to express the concept of "an IMagicThing which promises to be immutable" by defining an interface IImmutableMagicThing which derives from IMagicThing but adds no new members. A method which expects an IImmutableMagicThing won't accept any IMagicThing that doesn't implement the immutable interface, even if it happens to be immutable, but if one has a reference to an IMagicThing that happens to implement IImmutableMagicThing, one can cast that reference to the latter type and pass it to a routine that requires it.
Incidentally, there's one other usage I can see for an empty class type: as an identity token. A class need not have any members to serve as a dictionary key, a monitor lock, or the target of a weak reference. Especially if one has extension methods associated with such usage, defining an empty class for such purpose may be much more convenient than using Object.
I don't get the connection of Interfaces To polymorphism.
Polymorphism for me is about executing a method in a different way for some different concrete classes using abstract methods or virtual methods+ overriding and therefore this is only linked to inheritance in my vision, but how do you override methods With Interfaces??
How do you use Interfaces for doing same method in different ways and giving the object to decide what to do according to its concrete type?
Thanks
As stated by Andreas Hartl in his article on Inheritance Vs. Interfaces:
Many high-level languages support inheritance and interfaces, and for
someone new to the concepts, it's sometimes not clear which one to
choose. Although languages differ in their exact handling of
inheritance and interfaces, the basics are usually the same, so this
tip should be valid for most languages.
Inheritance means that we derive one class (the derived class) from
another class (the base class). The derived class is an extension of
the base class. It contains all the features (methods and data
members) of the base class, can extend it with new features, and can
reimplement virtual methods of the base class. Some languages, like
C++, support multiple inheritance, where a derived class can have
multiple base classes, but usually inheritance is restricted to a
single base class.
Interfaces can usually only define methods and no data members (but C#
for example allows data members in the form of properties within
interfaces), and a class can always implement multiple interfaces. An
interface contains only method definitions without implementations,
and a class that implements an interface supplies the implementation.
So, using inheritance, you write a base class with method
implementations, and when you derive a class from it, this class will
inherit everything from the base class, and is immediately able to use
its features. An interface on the other hand is just a contract of
method signatures, and a class that wants to implement an interface is
forced to supply the implementations for all methods of the interface.
So when do you use which? In some cases, the language already dictates
what you use: if you need your class to have multiple 'parents', you
cannot use inheritance in languages that don't support multiple
inheritance. And if you want to reuse a library object, you have to
use the fitting concept, depending on if that library object is a
class or an interface.
But which to use if you are free to choose? Basically, base classes
describe and implement common behavior of related types, while
interfaces describe functionality that unrelated types can implement.
Inheritance describes 'is a' relationships, interfaces describe
'behaves like' relationships. For example, say that you are writing a
flight simulator. Your basic entity, which you will for example store
in a list, will be 'Airplane'. Your concrete types will be 'Concorde'
and 'Phantom'. So how should you model the three types? Concorde and
Phantom are related, they both are airplanes and share data, like
'Weight' or 'MaxSpeed' and functionality, like 'Accelerate', so we can
model them with inheritance. 'Airplane' will be the base class with
common data and methods, and 'Concorde' and 'Phantom' will derive from
'Airplane'. We could say that both are specialized airplanes, which is
why it's often said that inheritance means specialization. Now assume
that we also add a class 'Pilot' to our program, and we want to give
the user the ability to save the game and load it later. So when he
saves the game, we need to save the state of all Aircrafts and the
state of all Pilots. And we want to do this in one function that takes
just a list of all saveable objects. So how do we model this? To
answer this, we must take a look at the different types we want to
save. Pilots and Airplanes. It's obvious that they are not related at
all. They share no common data and no common functionality. We can see
that writing a base class 'Saveable' and derive both Pilot and
Airplane from it would make little sense, since no code in Saveable
could be reused by Airplane or Pilot, since both have no common
properties. In this case, an interface is the best solution. We can
write an interface 'ISaveable' with a method Save(). Pilot could then
implement ISaveable.Save() by saving his name, while Airplane could
save its current speed and coordinates.
As you can see, a clear image of the relationship between classes
often makes the choice clear: Use inheritance for related types, where
each derived class 'is a' base class. Use interfaces for unrelated
types which have some common functionality.
Here are some more points to consider with inheritance and interfaces:
Interfaces are fixed. When you change an interface, you have to change every class implementing that interface. But when you change a
base class, every derived class will gain the new functionality, which
can both be good (if you make a bugfix in some base class method
implementation, a derived class using that method will gain the bugfix
without you needing to change it) or bad (if a change in the baseclass
introduces a new bug, all derived classes using the method will be
bugged too).
Interfaces are usually more flexible, since in most languages you can only derive from one class, but implement many interfaces
Interfaces help to protect internal classes: Assume class A has an internal object b of class B. When a method in A returns a pointer or
reference to b, the code that called this method now has access to the
whole object b, which can be dangerous if A only wants to expose
certain members of b. This problem can be solved if you create an
interface I with just the members which are safe to expose. When B
implements this interface, and your method in A returns b via an I
pointer or reference, the outside code can only do what you allow
through the interface.
Polymorphism as a concept does not require inheritance, although in many languages inheritance is the only way to achieve it. Some languages, like smalltalk allow you to polymorphically use any type that implements the same set of members and properties. If it looks like a duck, quacks like a duck, and walks like a duck, you can treat it like a duck.
Polymorphism is simply the ability to treat one object as another object, by providing the same way to access and use it as the original object. This is best illustrated by the Liskov Substitution Principle. This is called the "Interface" or sometimes "Contract", because it defines a "signature" that another object can use to do interesting things to the object.
in C#, you can inherit from interfaces or other (non-sealed) classes. The difference is that an interface does not provide any actual storage or methods (only their "signature"), it is merely a definition. You can't instantiate an interface, you can only instantiate an object that implements an interface.
Classes implement an interface (IDisposable, for instance) in the same way you build a house based on blue prints. If you build two houses with the same blueprints, then each house has the exact same "interface", they may have different color paint, or carpeting, but they function in exactly the same way, yet they are two distinctly different houses, with many differences in how various things might function.
When it comes to C#, just know that an interface says what properties or members an object that implements it MUST have. Likewise, in C#, a big difference is that you can inherit multiple interfaces but only ever a single class. (ie public class Test : BaseClass, IDisposable, ITest, IFooBar)
consider this...
public int SomeMethod(SomeBaseClass object)
{
// Pass in a descendant classe that implements / overrides some method in SomebaseClass
}
public int SomeMethod(ISomeInterface intf)
{
// pass in concrete classes that implement some ISomeInterface function
}
This is the basic essence of polymorphic behavior, a common contract, implemented specifically by a specialist class.
I feel like this should be very possible.
I have an interface, let's call it IJerry. Now, I have a class in variable x. That class implements IJerry perfectly. The thing is, that class does not ever reference IJerry. It just happens to have a perfect, compliant signature with IJerry.
Make sense? Let's say you create a class called MyClass that implements INotifyPropertyChanged. Then you delete the MyClass : INotifyPropertyChanged declaration from the class but you LEAVE the implementation inside the class.
Is there a way to determine if the class "implements" an interface even if it does not make an explicit reference to it?
Not easily.
You would have to read the fields, method, and properties of the interface using reflection, and then check if the class has them (again using reflection)
Alternately, if you are using C#4, you could just forget about IJerry, and put MyClass in a dynamic variable, and then you C# figure out at run-time for it has the methods being called.
There's a lot more to implementing an interface than meets the eye. For one, implementation methods are virtual, even though you don't use that keyword. In fact, you're not allowed to use that keyword. For another, the compiler rearranges the methods to match the method table layout of the interface. Removing the inherited interface from the declaration is guaranteed to make the result incompatible. The methods won't be virtual anymore.
What you are pursuing is called 'dynamic dispatch'. Implemented in the DLR and integrated into .NET 4.0 and the C# 4.0 language. Re-inventing the System.Reflection code and making it efficient is a major undertaking.
You would have to use reflection to see if x had methods that matched the ones on IJerry. The real question is, what are you going to do with the answer? Prior to version 4, C# doesn't support "duck typing", so in order to use your class where an IJerry is required you have to write adapter code.
I'm making a game where each Actor is represented by a GameObjectController. Game Objects that can partake in combat implement ICombatant. How can I specify that arguments to a combat function must inherit from GameObjectController and implement ICombatant? Or does this indicate that my code is structured poorly?
public void ComputeAttackUpdate(ICombatant attacker, AttackType attackType, ICombatant victim)
In the above code, I want attacker and victim to inherit from GameObjectController and implement ICombatant. Is this syntactically possible?
I'd say it probably indicates you could restructure somehow, like, have a base Combatant class that attacker and victim inherit from, which inherits from GameObjectController and implements ICombatant.
however, you could do something like
ComputeAttackUpdate<T,U>(T attacker, AttackType attackType, U victim)
where T: ICombatant, GameObjectController
where U: ICombatant, GameObjectController
Although I probably wouldn't.
Presumably all ICombatants must also be GameObjectControllers? If so, you might want to make a new interface IGameObjectController and then declare:
interface IGameObjectController
{
// Interface here.
}
interface ICombatant : IGameObjectController
{
// Interface for combat stuff here.
}
class GameObjectController : IGameObjectController
{
// Implementation here.
}
class FooActor : GameObjectController, ICombatant
{
// Implementation for fighting here.
}
It is only syntactically possible if GameObjectController itself implements ICombatant; otherwise, I would say you have a design problem.
Interfaces are intended to define the operations available on some object; base classes identify what that object is. You can only pick one or the other. If accepting the ICombatant interface as an argument is not sufficient, it might indicate that ICombatant is defined too narrowly (i.e. doesn't support everything you need it to do).
I'd have to see the specifics of what you're trying to do with this object in order to go into much more depth.
What if you did this instead:
public class GameObjectControllerCombatant : GameObjectController, ICombatant
{
// ...
}
Then derive your combatant classes from this instead of directly from GameObjectController. It still feels to me like it's breaking encapsulation, and the awkwardness of the name is a strong indication that your combatant classes are violating the Single Responsibility Principle... but it would work.
Well, sort of. You can write a generic method:
public void ComputeAttackUpdate<T>(T attacker, AttackType type, T victim)
where T : GameObjectController, ICombatant
That means T has to satisfy both the constraints you need. It's pretty grim though - and if the attacker and victim could be different (somewhat unrelated) types, you'd have to make it generic in two type parameters instead.
However, I would personally try to go for a more natural solution. This isn't a situation I find myself in, certainly. If you need to regard an argument in two different ways, perhaps you actually want two different methods?
If you control all the classes in question, and if GameObjectController doesn't define any fields, the cleanest approach would be to define an IGameObjectController (whose properties and methods match those of GameObjectController) and an ICombatantGameObjectContoller (which derives from both IGameObjectController and ICombatant). Every class which is to be usable in situations that require both interfaces must be explicitly declared as implementing ICombatantGameObjectController, even though adding that declaration wouldn't require adding any extra code. If one does that, one can use parameters, fields, and variables of type ICombatantGameObjectController without difficulty.
If you can't set up your classes and interfaces as described above, the approach offered by Jon Skeet is a generally good one, but with a nasty caveat: to call a generic function like Mr. Skeet's ComputeAttackUpdate, the compiler has to be able to determine a single type which it knows is compatible with the type of the object being passed in and with all of the constraints. If there are descendants of GameObjectController which implement ICombatant but do not derive from a common base type which also implements GameObjectController, it may be difficult to store such objects in a field and later pass them to generic routines. There is a way, and if you need to I can explain it, but it's a bit tricky.