Dynamic creation of object instances - c#

We have a system that creates dynamically defined objects as a core aspect of the processing. I would like to be able to create an class object and make these objects instances of this class, implementing all of the functionality that this particular object has.
The problem is, these objects really need to dynamically inherit from a base class, and override null methods etc. In essence, I need something of a dynamic class structure (and I have proposed compiling the definitions into a proper class model, but that is some distance away). The best approach i can come up with is to create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented.
I have also looked at Castles DynamicProxy approach, which might be a useful route (intercepting the calls and actioning them if appropriate), but this seems more complex than it should be.
So any suggestions? What would the best, most .Net-like approach to this be? As I look at the problem, it seems like there should be a really good and easy solution.
Just to help, a simple example (semi-pseudocode - I know it is not fully working):
class thing
{
public void Process()
{
foo();
bar();
}
private foo(){}
private bar(){}
}
a=new thing() {foo=DoFoo}
b=new thing() {bar=DoBar}
I want to be able to call a.Process and b.Process, and have them both run. Bear in mind that these objects have some 20-30 properties/methods that might need setting (setting them is easy, but some of them might be substantial methods)

create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented
This sounds a lot like the "decorator" design pattern might be a good choice for you here. You basically implement a set of functionalities and then build your objects by subsequently assigning several "decorations" (functionalities) to a baseobject.
http://www.codeproject.com/Articles/479635/UnderstandingplusandplusImplementingplusDecoratorp seems to be a very good summary with clear examples on how and when to use decorator patterns
However if your properties heavily interact with each other, or need a significant different implementation depending on other "decorations" i would not suggest using a decorator. In that case you might need to get a bit more specific on your requirements.

Not sure if I really understand your requirements, but have you looked at the DynamicObject class?
The idea behind it is that you derive from it, and every time a member is accessed, it gets a call to TryGetMember, TrySetMember, or TryInvokeMember for methods, where you can do your custom logic.
You can make a base class inheriting from DynamicObject then make the set of classes you want by deriving from that base class, implementing the logic on each one of them, this way you can have both defined members, and other non-defined ones which you can use using a dynamic type.
Check the documentation on MSDN for DynamicObject
Alternative
Otherwise, as a very simple solution and based on the pseudo-code you provided only (which admittedly might be a little simple for the requirements stated in the question), you could just make a Thing class which has Action properties:
class Thing
{
public void Process()
{
if(Foo!=null) Foo();
if(Bar!=null) Bar();
}
public Action Foo {get;set;}
public Action Bar {get;set;}
}
var a=new Thing() {Foo=DoFoo};
var b=new Thing() {Bar=DoBar};
a.Process();
b.Process();

Related

Alternative to static methods for interface

I understand that static methods are not correct for interfaces (see: Why Doesn't C# Allow Static Methods to Implement an Interface?) yet have come up against a situation where I have an object that implements all methods of an interface where all can be static, so I think I must be designing incorrectly.
Trouble is, I cant see any alternative
My interface IDataSerializer is implemented by several classes. One that de/serializes XML, one that does JSON, etc. All of these classes implement the same functions and none have any "state data" (members, etc), but all eventually result in the same type of object being output.
For example, the XML class:
public class MyXmlSerializer : IDataSerializer
{
public string SerializeFoo(object foo)
{
// uses .Net XML serialzer to serialize foo
}
public object DeserializeFoo(string foo)
{
// uses .NET XML serializer to deserialize foo
}
// Object type returned by above methods is only ever
// used by following method which returns a type available
// to all IDataSerializer implementations as this is
// the data actually used by the rest of the program
public IList<Bar> CreateBarList(object deserializedFoo)
{
// does some magic to extract a list of Bar from the
// deserialized data, this is the main work for any
// IDataSerializer implementation
}
}
Obviously all of the methods shown above could be static (they all take in all the info they need as parameters and all return the result of their working, there are no members or fields)... but because they should be implemented in a serializer that can do work for any type of serial data (XML,JSON, YAML, etc) then they form an interface... Which is it? Am I thinking about this wrong? Is there an alternative, specific, pattern for achieving what I want to do?
Afterthought: maybe I should simply change my idea of de/serialization being work that something can do to thinking of each implementation as is a serlializer, thus suggesting replacing interface with abstract class?
After-afterthought: overridden methods can't be static either, so changing to abstract class doesn't help any.
From logical point of view these methods should be static, because they logically don't work on a particular instance and don't use shared resources.This class don't have a state as well. But... from a pragmatic point of view, instant class brings many benefits, like:
class (interface) if fully testable,
follows the OOP and SOLID principles,
can be registered as singleton, so you can create only one instance of this object,
it's easy to add any dependencies to these classes
easy to maintain
some useful design patterns can be applied (e.g. decorator, composite)
can be lazy loaded and disposed in any time
In your case, in my opinion, you should hide this implementation behind the interface and register it as a singleton, e.g.(using autofac)
builder.RegisterType<MyXmlSerializer>().As<IDataSerializer>().SingleInstance();
In addition, if you need to, you can create an extension method for this interface and add static methods to this contract.
More information can be found here:
Instance methods vs static
Static class vs singleton
Extension methods

Different uses of Interfaces in C#

I read a lot about C# and had my first practical exercises, but I am still a beginner and kind of lost at a certain point of my try understanding an existing, but not finished, MVC-concepted program.
I understand what interfaces are for and how I must implement an interface to a class or another interface to gain acces to its containing members, functions etc, but in the existing code I found another use of interfaces (in the declaration of a class):
private IViewControl m_viewControl = null;
private IModelControl m_modelControl = null;
This code doesn't come up in the class, which implemented those two interfaces, but in the class which doesn't implement those two interfaces at all!
So my questions are:
How is this usage of interfaces called? It is clearly not the regular implementation of an interface.
What kind of possibilities do I get through this way of using an interface?
Thanks a lot!
Bent
Please excuse my english, I'm not a native speaker.
Hey,
thank you all so much for your answers, can't even say which is the best since all answers seem to be helpful! I think I'm starting to get what this is about.
Thanks again!
The class which contains these lines
private IViewControl m_viewControl = null;
private IModelControl m_modelControl = null;
Has 2 references to other classes which implement these Interfaces. So to answer your first question, this is not the implementation of an interface, it is the usage of an interface.
To answer your second question: That is exactly why we use interfaces. The class which uses these interfaces does not care about their implementation. In your development process you can write a dummy implementation for one or the other, because you don't need it right now, but you can still run and test the rest of the application.
An other example: Let's image you want to write an application which uses some Database. Put all your database logic behind an interface. In version 1 of your app you might use an SQL Database. Do your classes, which write to the database, know that it is an SQL database? No, and they don't need to. So now you move on and decide you want to use a different database system. You just change the implementation behind the interface and your done.
Hope this helps.
These are two variables (actually member variables, which are known as fields, as they are members of an enclosing type).
They can be used to store any item that implements the interface, so you could put anything that implements IViewControl into m_viewControl and anything that implements IModelControl into m_modelControl.
It does mean, that the object you can assign to your variable has to have the interface implemented.
So it has to be the type of the interface.
What you see there is called composition. It means that your class has two fields that are instances of those types, not that it is implementing their interfaces.
Let's use cars for an analogy. "Car" is a pretty generic concept, so let's make it the interface. The Toyota someone own is an instance of some class (e.g.: Corolla), which in turn implements the Car interface. The wheels, on the other hand, are fields of the car. The tires in your Corolla may belong to the Pirelli class, which implements the Tire interface. But your car is not a tire - it has tires.
An interface is a way to make a type without any implementation at all, but which cannot be instantiated. You can then have other types implementing that interface, giving it logic - so you have many variations of that interface, each doing something in a different way. The point is that you are making sure that all the implementors of an interface have a set of known method signatures and properties - you may not know how they are implemented, but you can be sure they are there.
If you look at some of the namespaces in C# that have a lot of classes implementing the same interface, you may get a better idea of how they behave. For example, a lot of classes in System.Collections implement the (surprise) ICollection interface. That makes sure that all collections have, for example, a Count property, and a CopyTo method with a known signature.
This type of usage is great to restrict the usage of a particular object, or to write common code that can work on any number of classes. Let's say we have a class called Car that implements an interface called IDriveable:
public class Car : IDriveable
Now, in some other class, we can instantiate a Car object easily, like so:
Car myCar = new Car();
But what if the Car class has several public methods that we don't want to be accessed in this other section? Or we want to write a function that can work on any class that implements the IDriveable interface? We could instead create an instantiation of the IDriveable interface itself, and then assign a Car to it, like so:
IDriveable myDriveable = new Car();
Then, if the following code works on the IDriveable interface, ANY class that implements IDriveable would work fine on it, such as this example:
private void TurnLeft(IDriveable vehicle)
P.S. Your English usage is great!
The important thing about interfaces is that you aren't interested in what they are but what they can do. Consequently in this case you are only interested in the IViewControl elements of whatever object is assigned to that local variable, so it could be of any class that implements IViewControl and very probably that class can do lots of other things as well, but for these purposes the fact that it is an IViewControl is all that we care about.
An example might be that we have a class that is interested in things that can fly, it doesn't care about anything else, so we create an interface called IFlyingThing with an IFlyingThing.Fly() method. Then we can have a Bird, Plane, Butterfly and all kinds of other types that implement IFlyingThing and we can pass it to our class and it will just see IFlyingThing and call IFlyingThing.Fly() which might be Bird.Fly(), or Plane.Fly() on the actual object it has been passed. It doesn't care what the object is, only that it can fly.
Bird might also implement IFeatheredAnimal, plane might implement IHasJetEngines too but our class is only interested in the IFlyingThing interface so it doesn't want or need to know about these.
This helps us to avoid tying our code together too tightly and makes techniques such as Inversion of Control and Mock Objects possible.
As you progress through learning C# you will use interfaces a lot.
Suppose you have a class, that you don't develop. You just consume it. You know it can generate some file and return it to you as a filestream. You don't know how it is generated, and you need not. You just know it returns you a filestream, which you then use for your own purpose. In order to implement it, you make a contract with a developer of the class that the class should provide you a method, which should return you a file stream and the name of the method should be ReturnStream, for example. This contract is called an Interface. By the time the developer of the class can change it's logic of file generation. But it would still have the same name ReturnStream and it would still return you a file stream. So you don't have to change anything in your code.
As for your code, you have two objects of IViewControl and IModelControl. You don't develop the model and view. You just consume the logic of other developers, who write the classes with the interface implementation. And you can use them in your code in a way you want. But many developers can create different classes, which implement IViewControl and IModelControl interfaces. And you can use them by simply changing the class instance, which implements the interface.
Doesn't sound like you've grasped properly how interfaces can be used. Let me enlighten you with a simple example:
class Driver{
// A driver has two cars - they are cars, since they are
// of types (classes Bmw and Audi) that implement the interface ICar:
ICar firstCar = MethodThatReturnsInstanceOfBmw();
ICar secondtCar = MethodThatReturnsInstanceOfAudi();
public void DriveAllCars(){
// The interface ICar has a method "Start()", which both
// cars must therefor implement. The Driver class can call
// these methods, because it knows about them from the interface.
firstCar.Start();
secondCar.Start();
}
}
The class Driver still does not need to implement ICar - just know about it (have a reference to it), so it knows what it can do with "things" of that type. It can then tell a car to Start(), without giving a rodents rear part about how the engine actually works.
Compare it to the real world: You don't need to be a car to drive, nor do you need to be a mechanic - you just need to know the basics of driving, and those are common to most cars, though engines and other things may differ greatly.
That abstraction and agreement on common functionality, is the purpose of interfaces.
Interface is basically used to implement similar feature among different classes.
Interface is also used to create object of class only when it is required via a dependency injection.
eg:
Interface IMyClass{}
Class MyClass1:IMyClass
{
}
and
IMyClass obj;
thus you can register obj with the class that implements IMyClass in one class(Bootstrapper) and inject obj into all the class through constructor or method that required it with out need of initializing it.
thus Interface Prevents unnessecary creation of object thus prevent memory leak and as I mentioned above it helps in implementing same feature among different classes in different way.

Object oriented design: when to make an abstract class

Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.

Can't specify static methods as part of an Interface?

I have a set of objects that I want to conform to an interface, say ISpecialObject.
However a part of my implementation I want to encapsulate the instantiation trigger of these specialobjects within the implementation of each ISpecialObject.
So say for instance I have as list of class types that implement ISpecialObject, I then want to go through each one and call a static method like CanCreate(some data) which tells me whether or not to create an instance of one of these.
However, .net doesn't seem to let me specify this static CanCreate as part of the ISpecialObject interface.
Can anyone suggest a way to get around this, or alternatively a better approach to solving the problem of encapsulation of the instantiation of these objects? I may just be thinking about this all wrong.
Thanks.
Edit: I may have phrased some parts of this poorly. I don't want to provide the implementation in the interface, but rather specify that there will be one, and that it will be static. Essentially I want the objects to be self defining by allowing a higher level object to query when to create them at runtime.
From what I understand, your main issue is the instantiation of a set of objects that conform to the same interface. If that is so, you may want to look at the Factory Design Pattern which is the standard way to encapsulate such logic.
.NET does not allow static method declarations on interfaces. They don't really make sense since interfaces are all about the contract and avoid implementation entirely. Static methods are specifically about implementation. Additionally, interface methods are virtual function calls depending on the type of the instance, whereas static methods are independent of an instance or even a class (they could be put on any concrete type).
If you have many implementations of ISpecialObject, you could use a factory pattern. In order to do this, you would define define an interface called ISpecialObjectFactory alongside ISpecialObject:
class ISpecialObjectFactory
{
ISpecialObject CreateInstance(...);
bool CanCreate(...);
}
Each class that implements ISpecialObject should have a corresponding ISpecialObjectFactory (e.g. UserObject would have also have a UserObjectFactory). This would require a bit more code, but it's a common pattern and I believe it solves your problem.
I dont see the issue. The typename is just a prefix when dealing with static methods. It will make no difference what so ever if the static method lives somewhere else.
That said, look at extension methods, which may do want you really want it to :)
Edit: Another option might be using attributes.
We just discussed something very similiar to this on another thread. Extension methods are definitely a way to solve this problem. They can provide an implementation for an interface, and the methods can be treated as static or used as a method on an instance of an object which is being extended.
It is not exactly a duplicate in the way that you've phrased the question, but it is duplicate in nature so check out the link below.
StackOverflow - subclass-needs-to-implement-interface-property-as-static
Maybe you can use an abstract class as super class for your purpose. So the static methods go in the abstract class and all derived classes have that as well. However, I agree to the the posts above that may be using the factory pattern is a better approach here.

Using The Interface Methods I Want Based On The Implementation

I have two basic interface-related concepts that I need to have a better
understanding of.
1) How do I use interfaces if I only want to use some of the interface
methods in a given class? For example, my FriendlyCat class inherits from
Cat and implements ICatSounds. ICatSounds exposes MakeSoftPurr() and
MakeLoudPurr() and MakePlayfulMeow(). But, it also exposes MakeHiss()
and MakeLowGrowl() - both of which I don't need for my FriendlyCat class.
When I try to implement only some of the methods exposed by the interface
the compiler complains that the others (that I don't need) have not been
implemented.
Is the answer to this that I must create an interface that only contains
the methods that I want to expose? For example, from my CatSounds class, I
would create IFriendlyCatSounds? If this is true, then what happens when
I want to use the other methods in another situation? Do I need to create
another custom-tailored interface? This doesn't seem like good design to me.
It seems like I should be able to create an interface with all of the
relevant methods (ICatSounds) and then pick and choose which methods I
am using based on the implementation (FriendlyCat).
2) My second question is pretty basic but still a point of confusion for
me. When I implement the interface (using Shift + Alt + F10) I get the interface's
methods with "throw new NotImplementedException();" in the body. What
else do I need to be doing besides referencing the interface method that
I want to expose in my class? I am sure this is a big conceptual oops, but
similar to inheriting from a base class, I want to gain access to the methods
exposed by the interface wihtout adding to or changing them. What is the
compiler expecting me to implement?
-- EDIT --
I understand #1 now, thanks for your answers. But I still need further elaboration
on #2. My initial understanding was that an interface was a reflection of a the fully
designed methods of a given class. Is that wrong? So, if ICatSounds has
MakeSoftPurr() and MakeLoudPurr(), then both of those functions exist in
CatSounds and do what they imply. Then this:
public class FriendlyCat: Cat, ICatSounds
{
...
public void ICatSounds.MakeLoudPurr()
{
throw new NotImplementedException();
}
public void ICatSounds.MakeSoftPurr()
{
throw new NotImplementedException();
}
}
is really a reflection of of code that already exists so why am
I implementing anything? Why can't I do something like:
FriendlyCat fcat = new FriendlyCat();
fcat.MakeSoftPurr();
If the answer is, as I assume it will be, that the method has no
code and therefore will do nothing. Then, if I want these methods
to behave exactly as the methods in the class for which the interface
is named, what do I do?
Thanks again in advance...
An interface is a contract. You have to provide at least stubs for all of the methods. So designing a good interface is a balancing act between having lots of little interfaces (thus having to use several of them to get anything done), and having large, complex interfaces that you only use (or implement) parts of. There is no hard an fast rule for how to choose.
But you do need to keep in mind that once you ship your first version of the code, it becomes a lot more difficult to change your interfaces. It's best to think at least a little bit ahead when you design them.
As for implementation, it's pretty common to see code that stubs the methods that aren't written yet, and throws a NotImplemented exception. You don't really want to ship NotImplemented in most cases, but it's a good get around the problem of not having the code compile because you havn't implemented required parts of the interface yet.
There's at least one example in the framework of "deliberately" not implementing all of an interface's contract in a class: ReadOnlyCollection<T>
Since this class implements IList<T>, it has to have an "Insert" method, which makes no sense in a read-only collection.
The way Microsoft have implemented it is quite interesting. Firstly, they implement the method explicitly, something like this:
public class ReadOnlyCollection<T> : IList<T>
{
public void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
/* ... rest of IList<T> implemented normally */
}
This means that users of ReadOnlyCollection<T> don't see the Insert method in intellisense - they would only see it if it were cast to IList<T> first.
Having to do this is really a hint that your interface hierarchy is a bit messed up and needs refactoring, but it's an option if you have no control over the interfaces (or need backwards compatibility, which is probably why MS decided to take this route in the framework).
You have to implement all the methods in your interface. Create two interfaces, IHappyCatSounds and IMeanCatSounds, split out those methods. Don't implement IMeanCatSounds in FriendlyCat, because a friendly cat is not a mean cat. You have to think about an interface as a contract. When you write the interface, you are guaranteeing that every class that implements the interface will have those members.
It throws a NotImplementedException because you haven't implemented it yet. The compiler is expecting you to implement the code that would be completed when the cat purrs, meows or hisses. An interface doesn't have code in it. It's simply nothing more than a contract for any class that implements it, so you can't really "access the code" the interface implements, because the interface doesn't implement any code. You implement the code when you inherit from the interface.
For example:
// this is the interface, or the "contract". It guarantees
// that anything that implements IMeowingCat will have a void
// that takes no parameters, named Meow.
public class IMeowingCat
{
void Meow();
}
// this class, which implements IMeowingCat is the "interface implementation".
// *You* write the code in here.
public class MeowingCat : IMeowingCat
{
public void Meow
{
Console.WriteLine("Meow. I'm hungry");
}
}
I'd strongly suggest picking up a copy of The Object Oriented Thought Process, and read it through in it's entirety. It's short, but it should help you to clear things up.
For starters, though, I'd read this and this.
Imagine that you could "pick and choose." For example, suppose you were allowed to not implement ICatSounds.MakeHiss() on FriendlyCat. Now what happens when a user of your classes writes the following code?
public ICatSounds GetCat()
{
return new FriendlyCat();
}
ICatSounds cat = GetCat();
cat.MakeHiss();
The compiler has to let this pass: after all, GetCat is returning an ICatSounds, it's being assigned to an ICatSounds variable and ICatSounds has a MakeHiss method. But what happens when the code runs? .NET finds itself calling a method that doesn't exist.
This would be bad if it were allowed to happen. So the compiler requires you to implement all the methods in the interface. Your implementation is allowed to throw exceptions, such as NotImplementedException or NotSupportedException, if you want to: but the methods have to exist; the runtime has to be able to at least call them, even if they blow up.
See also Liskov Substitution Principle. Basically, the idea is that if FriendlyCat is an ICatSounds, it has to be substitutable anywhere an ICatSounds is used. A FriendlyCat without a MakeHiss method is not substitutable because users of ICatSounds could use the MakeHiss method but users of FriendlyCat couldn't.
A few thoughts:
Interface Separation Principle. Interfaces should be as small as possible, and only contain things that cannot be separated. Since MakePlayfulMeow() and MakeHiss() are not intrinsically tied together, they should be on two separate interfaces.
You're running into a common problem with deep inheritance trees, especially of the type of inheritance that you're describing. Namely, there's commonly three objects that have three different behaviors in common, only none of them share the same set. So a Lion might Lick() and Roar(), a Cheetah might Meow() and Lick(), and an AlienCat might Roar() and Meow(). In this scenario, there's no clear inheritance hierarchy that makes sense. Because of situations like these, it often makes more sense to separate the behaviors into separate classes, and then create aggregates that combine the appropriate behaviors.
Consider whether that's the right design anyway. You normally don't tell a cat to purr, you do something to it that causes it to purr. So instead of MakePlayfulMeow() as a method on the cat, maybe it makes more sense to have a Show(Thing) method on the cat, and if the cat sees a Toy object, it can decide to emit an appropriate sound. In other words, instead of thinking of your program as manipulating objects, think of your program as a series of interactions between objects. In this type of design, interfaces often end up looking less like 'things that can be manipulated' and more like 'messages that an object can send'.
Consider something closer to a data-driven, discoverable approach rather than a more static approach. Instead of Cat.MakePlayfulMeow(), it might make more sense to have something like Cat.PerformAction(new PlayfulMeowAction()). This gives an easy way of having a more generic interface, which can still be discoverable (Cat.GetPossibleActions()), and helps solve some of the 'Lions can't purr' issues common in deep inheritance hierarchies.
Another way of looking at things is to not make interfaces necessarily match class definitions 1:1. Consider a class to define what something is, and an interface as something to describe its capabilities. So whether FriendlyCat should inherit from something is a reasonable question, but the interfaces it exposes should be a description of its capabilities. This is slightly different, but not totally incompatible, from the idea of 'interfaces as message declarations' that I suggested in the third point.

Categories