Change/Swap base class at runtime with another base class - c#

Sounds like silly idea but I was wondering if it's possible somehow.
Is it possible to change the base class of a derived class at runtime? Of course, there are lot of ifs and buts and the the question of why would someone do it and its a bad design probably and all that.
Keeping all those aside (even though they might be perfectly valid), let's say, just for kicks or to show your nerdiness, is it possible in C# or any language for that matter?
So something like:
public class baseOriginal {
public string justAProperty;
}
public class baseSwapped {
public int sillyNumber;
}
public class derivedClass : baseOriginal {
public bool iAmDumb;
}
void Main() {
baseOriginal derived = new derivedClass ();
Console.WriteLine(derived.justAProperty);
baseSwapped derivedSwapped = (??);
Console.WriteLine(derivedSwapped.sillyNumber);
}

It isn't possible in C#. Probably what you want is more of a prototype-based solution commonly found in dynamic languages like JavaScript where you can "extend" the functionality of the object by adding to how it's defined.
But to accomplish what your code hints at doing, you can have the swappable classes inherit from a common ancestor class. That way you can assign instances of each to their decendents.
public class baseClassAncestor{
}
public class baseOriginal:baseClassAncestor {
public string justAProperty;
}
public class baseSwapped:baseClassAncestor {
public int sillyNumber;
}
public class derivedClass : baseOriginal {
public bool iAmDumb;
}

You can do one time base class swap by loading different assemblies that implement base class BEFORE using derived class. But this approach will not make your exact code working as you will not be able to compile that - but moving access to methods of different base classes to separate functions could be made working.
You add UnionBase class that contains all possible methods/properties from all base classes so you can compile your Main code against the assembly with this class. Than at run time you load assembly that has contains your particular base class.
Usual warning: You need to have very good reasons and understanding for going this route. I.e. existing external code is a reason to consider such approach.
"Don't do it at home, performed on a closed course by trained professional".

One more possible workaround could be implemented using some AOP solution that is based on compile-time weaving, i.e. PostSharp, which is able to seamlessly inject new methods and interfaces to existing types as well as modify (intercept) existing ones.

There is actually a good reason where you may want to swap the base class. Let say you want to modify the base class but you don't wan't to perturb the current code base as it is shared among other teams. Let say there are 10+ derived class that inherits from base. You could create 10+ custom derived classes to override the base class but that is a lot of work. Here is what you do. The key to the problem is to create an interface and a base proxy class.
class Program
{
static void Main(string[] args)
{
IActionable action = new Derived<Base1>();
action.open();
action = new Derived<Base2>();
action.open();
}
}
// Proxybase is a fake base class. ProxyBase will point to a real base1 or
// base2
public class Derived<T>:ProxyBase,IActionable
{
public Derived():base(typeof(T))
// the open function is not overriden in this case allowing
// the base implementation to be used
}
// this looks like the real base class but it is a fake
// The proxy simply points to the implementation of base1 or base2 instead
public abstract class ProxyBase: IActionable
{
IActionable obj;
public ProxyBase(Type type,params object[] args)
{
obj = (IActionable)Activator.CreateInstance(type,args);
}
public virtual void open()
{
obj.open();
}
}
// notice base1 and base2 are NOT abstract in this case
// consider this the original implementation of the base class
public class Base1: IActionable
{
public virtual void open()
{
Console.WriteLine("base1 open");
}
}
// here base2 acquired the functionality of base1 and hides base1's open
function
// consider this implementation the new one to replace the original one
public class Base2: Base1, IActionable
{
public new virtual void open()
{
Console.WriteLine("base2 open");
}
}
public interface IActionable
{
void open();
}
The result would be as follows
base1 open
base2 open
UPDATE:
Although this answer works, the reality is that inheritance introduces coupling which makes this exercise difficult at best. Also, in a practical scenario, your requirements may lead you to want to derive from multiple base class which is not possible in c#. If you want to interchange the base class you are best to use the bridge design pattern (which in fact avoids inheritance altogether thus avoiding the coupling).

The closest thing I can think of is the following:
http://msdn.microsoft.com/en-us/library/dd264736.aspx
static void Main(string[] args)
{
ExampleClass ec = new ExampleClass();
// The following line causes a compiler error if exampleMethod1 has only
// one parameter.
//ec.exampleMethod1(10, 4);
dynamic dynamic_ec = new ExampleClass();
// The following line is not identified as an error by the
// compiler, but it causes a run-time exception.
dynamic_ec.exampleMethod1(10, 4);
// The following calls also do not cause compiler errors, whether
// appropriate methods exist or not.
dynamic_ec.someMethod("some argument", 7, null);
dynamic_ec.nonexistentMethod();
}
class ExampleClass
{
public ExampleClass() { }
public ExampleClass(int v) { }
public void exampleMethod1(int i) { }
public void exampleMethod2(string str) { }
}
I have no idea if the dynamic language runtime can do what you want it to do.
Closest you could get would be to
derive from both types by defining at
least one as an interface, then
casting derived from one to the other.
I would have to agree, based on the example this suggestion would satisfy what he wants to do, it also is a better design then what he actually wants to do.

Closest you could get would be to derive from both types by defining at least one as an interface, then casting derived from one to the other.

Related

How to reference abstract class

When posting this question my hope was to find a way how to reference/point to
an abstract class that that could be used by a worker/holder.
As the comments by #progman suggested and #laryx-decidua there is no way to hold a reference to an abstract class, but one can only hold a reference to a instantiated object.
Below you can find what I think is their proposed solution. To me this is an ugly solution, and I would have liked to have one that derives multiple static classes from an abstract base class and the holder gets references to those static classes to do its work. Deriving a static class form an abstract class Why you can't drive a static class is it seems prohibited by design and indicates bad architecture; although I don't see why the solution above is any better.
Suggested Solution
using System;
using System.Collections.Generic;
public abstract class BaseClass
{
// Some declarative knowledge
public int value;
protected BaseClass(int value){
this.value = value;
}
// Some procedural
public abstract void execute();
}
public class ConcreteClass1 : BaseClass
{
public ConcreteClass1() : base(42) {}
public override void execute()
{
Console.WriteLine("In Concrete1! Value " + value);
}
}
public class ConcreteClass2 : BaseClass
{
public ConcreteClass2() : base(8888) { }
public override void execute()
{
Console.WriteLine("In Concrete2! Value " + value);
}
}
public class Holder
{
BaseClass activeClass;
public void setClass(BaseClass newClass){
activeClass = newClass;
}
public void doWork()
{
int x;
activeClass.execute();
x = activeClass.value * activeClass.value;
Console.WriteLine("Holder has done its work: " + x);
}
}
class MainClass
{
static void Main(string[] args)
{
List<BaseClass> classes = new List<BaseClass>();
classes.Add(new ConcreteClass1());
classes.Add(new ConcreteClass2());
Holder holder = new Holder();
holder.setClass(classes[0]);
holder.doWork();
holder.setClass(classes[1]);
holder.doWork();
holder.setClass(classes[0]);
holder.doWork();
}
}
producing
In Concrete1! Value 42
Holder has done its work: 1764
In Concrete2! Value 8888
Holder has done its work: 78996544
In Concrete1! Value 42
Holder has done its work: 1764
Disclaimer: I don't speak C#, but I suspect the situation is similar to C++. The rest of the answer is based on my C++ and general OOP experience.
If I understood you correctly, you'd like to hold derived class object(s) through a base class reference and invoke a polymorphic ("virtual") method on those objects. Because you expect those derived classes to be "stateless" (i.e. no data members), you thought maybe you could "get away with" static (and/or abstract) classes.
The problem is that you need to instantiate something to put into your Holder objects, because a reference (or a pointer) can refer to (point to) only to a concrete object. So you need to instantiate objects that will be referred to via a reference in Holder, as some of the commenters have already pointed out. That's why abstract classes won't do -- they cannot be instantiated.
If there were an OOP language that supports references to types , plus some mechanism that can do the following: "Hmm, here is a reference AnimalTypeRef to the (possibly abstract) base class type Animal. AnimalTypeRef actually refers to the derived class type Elephant. Now, the user wants to invoke a virtual method Animal::make_noise() that does not use any class state, so let's invoke the corresponding method Elephant::make_noise() that overrides it and returns this :-)." -- well, then you could do what you have asked for.
I suspect this has not been implemented in C++ or C# because there are not too many use cases for it, and actually the same thing can be done with the general mechanism that requires that references refer to concrete objects.
Just go ahead and derive concrete (non-abstract) classes from your abstract base class, and don't worry about their statelessness. It's perfectly OK to define and use concrete objects that have no data members. Instantiate them, then initialise a Holder object with them, using a reference to the (abstract) base class and that's it. Polymorphic method invocation through base class references will do the rest.

Factory Pattern to build many derived classes

I have a factory object ChallengeManager to generate instances of a Challenge object for a game I'm building. There are many challenges. The constructors for each Challenge class derivation are different, however there is a common interface among them, defined in the base class.
When I call manager.CreateChallenge(), it returns an instance of Challenge, which is one of the derived types.
Ideally, I would like to keep the code for the object construction inside the derived class itself, so all the code related to that object is co-located. Example:
class Challenge {}
class ChallengeA : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeA();
}
}
class ChallengeB : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeB();
}
}
Now, my ChallengeManager.CreateChallenge() call only needs to decide the class to call MakeChallenge() on. The implementation of the construction is contained by the class itself.
Using this paradigm, every derived class must define a static MakeChallenge() method. However, since the method is a static one, I am not able to make use of an Interface here, requiring it.
It's not a big deal, since I can easily remember to add the correct method signature to each derived class. However, I am wondering if there is a more elegant design I should consider.
I really like the pattern you are describing and use it often. The way I like to do it is:
abstract class Challenge
{
private Challenge() {}
private class ChallengeA : Challenge
{
public ChallengeA() { ... }
}
private class ChallengeB : Challenge
{
public ChallengeB() { ... }
}
public static Challenge MakeA()
{
return new ChallengeA();
}
public static Challenge MakeB()
{
return new ChallengeB();
}
}
This pattern has many nice properties. No one can make a new Challenge because it is abstract. No one can make a derived class because Challenge's default ctor is private. No one can get at ChallengeA or ChallengeB because they are private. You define the interface to Challenge and that is the only interface that the client needs to understand.
When the client wants an A, they ask Challenge for one, and they get it. They don't need to worry about the fact that behind the scenes, A is implemented by ChallengeA. They just get a Challenge that they can use.
You're "decentralizing" the factory, such that each subclass is responsible for creating itself.
More commonly you would have a central factory that would know about the possible subtypes and how to construct them (often enough, simply by creating a new instance and returning that instance typed as a common interface or common base class). That approach avoids the issue you currently have. I also see no benefit to your current approach. You are currently gaining no encapsulation or code reuse over the more typical implementation of a factory.
For additional reference, have a look at
http://www.oodesign.com/factory-pattern.html
Not necessarily the answer you are looking for but...
You can use following implementation, if you can move away from static method per class.
using System;
public class Test
{
public static void Main()
{
var c1 = ChallengeManager.CreateChallenge();
var c2 = ChallengeManager.CreateChallenge();
//var c = ChallengeManager.CreateChallenge<Challenage>(); // This statement won't compile
}
}
public class ChallengeManager
{
public static Challenage CreateChallenge()
{
// identify which challenge to instantiate. e.g. Challenage1
var c = CreateChallenge<Challenage1>();
return c;
}
private static Challenage CreateChallenge<T>() where T: Challenage, new()
{
return new T();
}
}
public abstract class Challenage{}
public class Challenage1: Challenage{}
public class Challenage2: Challenage{}

Is it not the waste of time to create abstract classes?

I am so confused about the abstract classes I know it is not a question related to programing problem.But this is the only place I can find solution for this.
As everybody know that abstract classes cannot be instantiated and you cannot implement anything in these classes. We can just derive these classes and can do implementation in derived classes. So my question is this:
If we have to implement logic in derived classes and we have to use complete function and classes in derived class then why we create abstract classes?
Can anybody give me a clear explanation for this? If there is any good example then please tell me
When you use an abstract class you have some implementation in the abstract class, but leave bits that are specific to a derived class as abstract. For example, I might define an abstract class for all shapes:
abstract class Shape
{
public int Sides{get;protected set;}
public abstract int CalculateArea();
}
All shapes have a particular number of sides, so that can go into the general case (ie Shape). The calculcation of the area depends on the type of shape (triangle, square etc) so if belongs in the derived class. However, I'd like users of my class hierarchy to be able to call CalculateShape from any Shape instance.
How I create a derived class and override CalculateLength:
class Square : Shape
{
public Square(int sideLength)
{
this.Sides = 4;
this.SideLength = sideLength;
}
public int SideLength{get;private set;}
public override int CalculateArea()
{
return this.SideLength * this.SideLength
}
}
Note that I haven't reimplemented all of Shape in Square, I have only implemented the Square specific bits.
According to MSDN,
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
The above are all the technical explanation, in layman style it's like creating a blueprint that provide info what all things it can do, and all the derived classes will provide there own process how to do that.
For example, we can think of Driver and we know there are many driver types like auto-rickshaw driver, truck driver, tractor driver etc. but all have a common denominator functionality that is Driving but each of Driving process will be different, thus
Driver: abstract class with Driving function
Auto-RickshawDriver: Derived class extending Driver class
Your question,
If we have to implement logic in derived classes and we have to use complete function and classes in derived class then why we create abstract classes?
Just because we want to define some common functionality, that every other class has to abide to be member of it. In general term creating groups based on functionality, i.e. we can say if that class belong to a group we are damn sure that those common functionality of that group will be present.
Abstract classes will contain common incomplete implementation which can then be reused from multiple derived classes.
protected methods inside it can only be called from inside the derived classes.
abstract methods need to be implemented in derived classes.
virtual methods can be ocerriden in derived classes
In .NET framework you can find many examples of such abstract classes, e.g. System.IO.Stream.
The code using all those classes can refer to them using their common public interface of Stream, not having to know which concrete Stream implementation it uses.
Just to correct a minor detail, abstract classes can be partially abstract or fully abstract, depending on whether they are partially implemented (in which case we commonly call them abstract classes) or not implemented at all and have no member variable (in which case we commonly call them interfaces).
They are many uses for abstract classes, most of them implying the ability to extend behaviour of code without modifying this code.
Let's suppose that you want to write a program that reads data from the keyboard and writes it to the screen. (I'll use C# for the code, because it's slightly shorter than C++)
void Copy() {
int c;
while((c = Console.Read()) != -1) {
Console.Write(c);
}
}
Now, the requirements change. You want to be able to read from a file instead of the keyboard, depending on a variable.
TextReader reader;
void Copy(bool readFromFile) {
int c;
while((c = ReadNextChar(readFromFile)) != -1) {
Console.Write(c);
}
}
int ReadNextChar(bool readFromFile) {
if(readFromFile) {
return reader.Read();
} else {
return Console.Read();
}
}
Now, you want to be able to read from the network. The bool becomes an enum, the if/else becomes a switch/case etc. etc.
enum ReadMode { FROM_CONSOLE, FROM_FILE, FROM_NETWORK };
TextReader fileReader;
TextReader networkReader;
void Copy(ReadMode readMode) {
int c;
while((c = ReadNextChar(readMode)) != -1) {
Console.Write(c);
}
}
int ReadNextChar(ReadMode readMode) {
switch(readMode) {
case FROM_CONSOLE:
return Console.Read();
case FROM_FILE:
return reader.Read();
case FROM_NETWORK:
return networkReader.Read();
default:
return -1;
}
}
And this can go on. And the same requests may occur for the writing. The problem with this program is that it explicitly lists all the ways you can read from a file. To read from another source, you have to modify the code (add a member to the enum ReadMode and add a case in ReadNextChar. You may deem this OK if you have access to the source code, but if it's an external library, you may deem crappy this way of doing because you can not extend this wonderful copy library.
Now meet abstract classes. What if you abstracted all the sources into a single Source concept, because after all, all you need is to ask the source for an int. So let's write this abstract concept.
interface Source {
int ReadNextChar();
}
And all three implementations:
class KeyboardSource : Source {
int ReadNextChar() {
return Console.Read();
}
}
class FileSource : Source {
TextReader reader;
FileSource(string path) {
reader = new StreamReader(path);
}
int ReadNextChar() {
return reader.Read();
}
}
class NetworkSource : Source {
TextReader reader;
NetworkSource (string url) {
reader = new StreamReader(path);
}
int ReadNextChar() {
return reader.Read();
}
}
And implement the copy function:
void Copy(Source source) {
int c;
while((c = source.ReadNextChar()) != -1) {
Console.Write(c);
}
}
Now any source type you want to add, you just have to implement a new derivative of Source, without modifying existing code. The Copy program remains correct and untouched, so do the existing derivatives of Source.
This is called polymorphism. If you look at the dependencies of the Copy, they don't include code concerning either files, network, or user interface. It can be packaged in a library, allowing users to extend the types of sources from which it can read.
Hope it's clear. The same can be done for the writing part.
Regard this example:
abstract class A
{
// forces subclasses to implement
abstract void method1();
virtual void method2()
{
// some common logic
// that sublcasses can
// modify
}
protected void method3()
{
// some common logic
}
}
class B : A
{
void method1()
{
// needs to be implemented
}
override void method2()
{
// optional: e.g. something added
base.method1();
}
}
class C : A {
//...
}
No you can specify common logic in the base class, as well as define abstract methods that every subclass will have. So your baseclass works like an interface. You can call method1() to every instance of B and C.
So: No! It's absolutely no waste of time ;-).
It's not,
Assume you have a base class
class Foo{
public String getGreetingMessage(){
return "Hello " + getName();
}
public abstract String getName();
}
and you have a derived class
class Bar extends Foo{
public String getName(){
return "MeMamo";
}
}
class Boo extends Foo{
public String getName(){
return "Boo";
}
}
And in another class, I call the method from derived,
Bar b = new Bar();
System.out.println(b.getGreetingMessage()); // Hello MeMamo.
Boo boo = new Boo();
System.out.println(boo.getGreetingMessage()); // Hello Boo;
I don't need to write the base method all over again.
Assume that operation for another derived class.

How to create a base class with static factory method in C#?

I have need to use one of two custom file readers classes; one to read a fixed width file and one for a CSV file. Each of these readers will have certain properties, etc. I want to use factory methods and have private constructors so I can run some business logic before creating the objects.
EDIT: better examples
//simple class with it's own factory method
class Class1
{
private Class1()
{
//constructor code
}
public static Class1 CreateClass()
{
//do some business logic here
return new Class1();
}
}
What I want to be able to do is define a base class, then override the factory. I guess the problem is that a static class belongs to the base CLASS, so can never be overriden, even though they ARE inherited. This code works
public class BaseClass
{
//some common properties / fields here
public string SomeField;
//some common methods here
//empty constructor
protected BaseClass() { }
//cannot have a virtual static class!
//Would really like to make this a virtual method
public static BaseClass CreateClass()
{
throw new NotImplementedException("BaseClass is meant to be derived");
}
public static string DoCommonStaticThing(){
return "I don't know why you'd ever do this";
}
}
public class DerivedClass1 : BaseClass
{
//private constructor
private DerivedClass1() {}
//concrete factory method
//would really like to say "override" here
public static BaseClass CreateClass()
{
DerivedClass1 d1 = new DerivedClass1();
d1.SomeField = "I'm a derived class\r\n" + DoCommonStaticThing();
return d1;
}
}
EDIT: To clarify further, what I'm trying to do is put some common functionality in my base class, but define an interface for my file-format-specific methods. Some of the methods are common, but the business logic for the constructor(s) is file format specific. My code above works, but it seems to me it would be better to mark the base class factory method as virtual, and the derived class factory method as "override".
I tried to do this, but got "A static member cannot be marked as override, virtual, or abstract".
What's the right way to achieve my goals?
First, explaining your specific error message: you cannot inherit static members because they belong to the type being defined, not the instance of the type. Inheritance modifiers such as override, virtual, and abstract do not apply to static members.
Second:
Typically when you follow a factory pattern, you have a factory class whose job is to instantiate concrete classes and return those instances cast as a base class or interface. Details vary as to how the factory chooses which concrete class to instantiate, and I won't get into that, but at the fundamental level, that's what a factory does.
So in order to create a factory pattern using the example you provided, you'll need at least four types, which, following your example, could probably be named ReaderBase, ReaderFactory, CsvReader, and FixedWidthReader. Rather than ReaderBase, you might consider IReader -- the choice depends on whether your abstract class pre-implements any functionality that is shared across all Readers.
CsvReader and FixedWidthReader inherit from either IReader or ReaderBase, and ReaderFactory has at least one method called, for example, InstantiateReader, which returns an IReader or ReaderBase. InstantiateReader does the work of determining whether to instantiate a CsvReader or a FixedWidthReader, based on some external criteria.

Interface wonder question

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();
}

Categories