Why we do create object instance from Interface instead of Class? - c#

I have seen an Interface instance being generated from a class many times. Why do we use interface this way? An interface instance is created only itself with the help of the derived class and we can access only these interface members through this instance. How does this give an advantage? I'm so confused.
interface IPrint
{
void Print();
}
class Sample : IPrint
{
public void Print()
{
Console.WriteLine("Print...");
}
public void Sample()
{
Console.WriteLine("Sample...");
}
}
class Program
{
static void Main(string[] args)
{
IPrint print = new Sample();
print.Print();
}
}

Interfaces define that a class MUST be able to do something. This means that you know the object being worked on will do what you want to be able to do. It allows you greater freedom and is one of the advantages of OOP. This is a deep topic but a very basic example would be this:
public interface IAnimal
{
string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "Woof, woof";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "Meow";
}
}
public class Parrot : IAnimal
{
public string Speak()
{
return "Sqwark!";
}
}
Then you could use any animal you like!
class Program
{
static void Main(string[] args)
{
// Writes Woof, Woof
IAnimal animal = new Dog();
Console.WriteLine(animal.Speak());
// Now writes Meow
animal = new Cat();
Console.WriteLine(animal.Speak());
// Now writes Sqwark etc
animal = new Parrot();
Console.WriteLine(animal.Speak());
}
}
This also allows you to then get into things like Inversion Of Control where you would take an item in like this and you could pass a dog, cat or parrot and the method would always work, not knowing or caring which animal it was:
public void ShoutLoud(IAnimal animal)
{
MessageBox.Show("Shout " + animal.Speak());
}
This then makes ShoutLoud unit testable because you could use a mock object rather than a real animal. It basically makes your code flexible and dynamic rather than rigid and tightly coupled.
Also, expanding on Matthew's question. In C# you can only inherit from one base class but you can have multiple interfaces. So, you could have:
public class Dog : IAnimal, IMammal, ICarnivor
This allows you to have small interfaces (recommended) that then allow you to build up so giving maximum control over what an item can / must do.

Using an interface this way gives you the ability to create methods that use standard template of the interface. So here you might have many classes of printer that all inherit from IPrinter
class SamsungPrinter : IPrinter
{
// Stuff and interface members.
}
class SonyPrinter : IPrinter
{
// Stuff and interface members.
}
interface IPrinter
{
void Print();
}
So for each type SamsungPrinter, SonyPrinter, etc. you can pre-process using something like
public static void PreProcessAndPrint(IPrinter printer)
{
// Do pre-processing or something.
printer.Print();
}
You know from inheriting from IPrinter and using that type in the method parameters that you can always safely use the Print method on what ever object is passed.
Of course there are many other uses for using interfaces. One example of their use is in design patterns, in particular the Factory and Strategy patterns. The description of which and examples can be found here.
I hope this helps.

But how does this differ from, for example, using a base class with virtual methods?
You are all in the assumption that one programmer or one program writes the interface and the classes, but this doesn't always have to be this way.
Maybe you have a complete finished program that works with animals and you have this worked out using:
public abstract class Animal { public abstract string Speak(); }
And then some day you download some awesome DLL from nuget that shows pictures for animals. The class library contains a contract - interface - 'IAnimal':
namespace AwesomeAnimalLibrary
{
public interface IAnimal
{
string AnimalName;
}
}
The class library also maybe contains :
namespace AwesomeAnimalLibrary
{
public class AnimalPhotos
{
[Byte] GetPhotos(IAnimal animal);
}
}
What could you do now ? Your bas class Animal can implement the AwesomeAnimalLibrary IAnimal interface and that's it.
Don't assume that other people will use you abstract base classes but work together using interface contracts.

Interface can not have instance because interface implements only signatures of properties or methods. Interface is just a pointer to an instance of some class:
interface IExample
{
// method signature
void MyMethod();
}
public class MyClass : IExample
{
// method implementation
public void MyMethod()
{
ConsoleWriteline("This is my method");
}
}
// interface pointing to instance of class
IExample ie = new MyClass();
ie.MyMethod();

Related

Accessing objects through their interfaces

What does it really mean? I am reading design pattern book. It says
objects are accessed solely through their interfaces, and I am not able to get my head around it, can some body give me an example (Will really appreciate if its in C#)
What do we really achieve by using it?
Thanks
If you have a class called Espson and it implements an interface called IPrinter then you can instantiate the object by it's interface.
IPrinter printer = new Espson();
Epson may have a number of methods that are not part of the IPrinter interface but you may not care. All you may want to do is call a method defined in the IPrinter interface called Print
So then I can pass the class to a method called PrintDocument(IPrinter printer) and the method doesn't care what type of printer it is, it just knows it has a method called Print
The problem is the interface has several meanings. In this case the author is talking that objects must be accessed through public methods (in C# through public properties also) only.
(Of course, inheritors may use protected methods).
Public methods/properties form the public interface of a class. It's not the same interface that described by interface keyword in C#.
That really depends. If the variable is of type "interface", then in that case the object can be accessed by the interface type only.
Let's consider an example - Suppose I have an interface as defined below -
interface IMyInterface
{
string B();
}
and if I implement this interface using a class "MyClass" as shown below -
public class MyClass:IMyInterface
{
public string B()
{
return "In Class";
}
}
public class MyAnotherClass:IMyInterface
{
public string B()
{
return "In Another Class";
}
}
and I create an instance of the class using the interface as shown below
IMyInterface myinst = new MyClass();
then in the above case I can only get access to the Method B() using variable myinst which contains a reference to MyClass type.
Going further, let's say I have a method that takes a parameter of type IMyInterface as shown below -
public class UseOfInterface{
public void InterfaceUse(IMyInterface myPara)
{
myPara.B();
}
}
and I call this method as shown below -
IMyInterface myInst = new MyClass();
IMyInterface myAnotherInst = new MyAnotherClass();
UseOfInterface interfaceUse = new UseOfInterface();
interfaceUse.InterfaceUse(myInst); // returns "In Class"
interfaceUse.InterfaceUse(myAnotherInst); // returns "In Another Class"
Then, as shown above, it is decided at runtime as to which method is called using the Interface variable.
But if I had created a variable of type MyClass which would have contained a reference of type MyClass itself as shown below -
MyClass myinst = new MyClass();
then method B() can be accessed using the MyClass instance. So it depends what type of scenario you are dealing with.
Edit: Why Use Interfaces?
The main reason to use an interface is that it provides a contract to the class for which it is being implemented apart from the multiple inheritance support in C#. Let's can see an example where the contract providing can be helpful.
Suppose you have a class - "Car" in your assembly that you want to expose publicly, the definition of the class is as shown below
namespace CarNameSpace
{
public class Car()
{
public void Drive(IDriver driver)
{
if(driver.Age > 18)
{
driver.Drive();
}
}
}
}
As shown above, anyone who implements the IDriver interface can drive the car, which is defined below,
interface IDriver
{
string Age{get; set;}
string Name {get set;}
string Drive()
}
In turn to drive my car I would be exposing the IDriver interface to the outer world, so anyone who implements my interface can call the Car's Drive method, doesn't matter how he drives the car as shown below
public class PerfectDriver:IDriver
{
public PerfectDriver()
{
Name = "Vikram";
Age = 30;
}
public int Age{get; set;}
public string Name {get; set;}
public string Drive()
{
return "Drive's perfectly";
}
}
The Car class can be used as shown below
PerfectDriver perf = new PerfectDriver
Car myCar = Car();
myCar.Driver(perf);
An interface is a construct that describes the signature of the public members of an object. It contains declarations (declarations only, no implementation) of properties, methods and events that are guaranteed to be present on any object that implements that interface.
Here's a simple interface and a few classes that implement it. The interface "INamed" states simply that objects implementing the interface have a "Name" property that is a string.
public interface INamed{
string Name{get;}
}
public class Person : INamed{
public string Name{get;set;}
}
public class Place : INamed{
public string Name{get;set;}
}
public class Thing : INamed{
public string Name{get;set;}
}
...And a simple method that accepts a parameter of that interface type.
static void PrintName(INamed namedObject){
Console.WriteLine(namedObject.Name);
}
This "PrintName" method can accept a parameter of any type that implements that interface. The advantage of "accessing objects by their interface" is that it infuses your application with a certain flexibility, accessing these interfaces as opposed to their concrete types allows you to operate on these objects without having to know what they really are.
I could, for instance choose to operate on the IDbCommand interface as opposed to a concrete SqlCommand and much of what I write in this manner will be useful when working with a variety of database providers.
The simple idea is that you don't need to know if you're in a car or a boat because you can drive anything with a wheel and pedals.
The interface refers to what the object exposes to users of the object. An object will be an instance of a class which will have its own interface and possibly implement one or more other interfaces.
While languages such as C# allow you to define things called interfaces, those are distinct from the interface referred to in the statement that objects are accessed through their interfaces. In a language such as Scala, for instance, what C# calls an interface is called a trait. Most design patterns do involve the use of defined interfaces, i.e. public interface <interface name>, but again, those are distinct from what is meant in the original statement.
Suppose I define the following class in C#:
public class MyType
{
public void Method1()
{
...
}
private void Method2()
{
...
}
public int Method3()
{
...
}
}
Then the interface through which I interact with the class is the two methods it exposes, void Method1 and int Method2 and the implicit parameterless constructor.
Now, suppose I define the following interfaces and class:
public interface IInterface1
{
void Method1();
}
public interface IInterface2
{
int Method3();
}
public class MyType2 : IInterface1, IInterface2
{
public void Method1()
{
...
}
private void ADifferentMethod()
{
...
}
public int Method3()
{
...
}
}
The interface through which a user interacts with instances of MyType2 is the same as that through which a user interacts with instances of MyType1 (except for the different constructors) because the signatures of the public methods (and other public members) are identical : void Method1 and int Method3.

Force a class implementing interface A to also inherit from a type derived from interface B

what I want is that if class A implements my interface (B) I also want A being forced to implement an interface/type derived from type C.
In code, the result would look like this:
public interface SomeInterface
{
// implementing this interface forces the implementing class to also implement
// a derived interface/type of SomeBaseInterface
void SomeMethod();
}
public interface SomeBaseInterface
{
void SomeBaseMethod();
}
public interface SomeOtherInterface : SomeBaseInterface
{
void SomeOtherMethod();
}
public class ImplementingClass : SomeInterface, SomeOtherInterface // <- if not
// implementing an interface/type derived from SomeBaseInterface
// this should not compile
{
public void SomeMethod()
{
}
public void SomeOtherMethod()
{
}
public void SomeBaseMethod()
{
}
}
*edit
it would also work to 'mark' SomeBaseInterface as not inheritable by a class. Meaning that only another interface/abstract class can inherit from it. not possible, see C# Interfaces- only implement an interface in other interfaces
I don't think you can force the use of one interface when using another, unless you derive one interface from the other. However, you could use attributes and set up a unit test that would check your code for you.
[MyInterfaceCheck(typeof(IMyBaseInterface))]
public interface IMyInterfaceA {...}
public interface IMyBaseInterface {...}
public interface IMyInterfaceB : IMyBaseInterface {...}
public class MyClass : IMyInterfaceA, IMyInterfaceB {...}
The attribute would be defined simply as:
public class MyInterfaceCheckAttribute : Attribute
{
public MyInterfaceCheckAttribute(Type typeThatShouldAlsoBeInherited)
{
if (!typeThatShouldAlsoBeInherited.IsInterface)
{
throw new ArgumentException("Incorrect type being used with MyInterfaceCheckAttribute.");
}
TypeThatShouldBeInherited = typeThatShouldAlsoBeInherited;
}
public Type TypeThatShouldBeInherited { get; private set; }
}
And the Unit Test:
[TestMethod]
public void CheckInterfaceInheritenceTest()
{
Dictionary<Type, MyInterfaceCheckAttribute> typesToCheck = new Dictionary<Type, MyInterfaceCheckAttribute>();
foreach (Type typeToCheck in Assembly.GetExecutingAssembly().GetTypes())
{
MyInterfaceCheckAttribute myAtt = typeToCheck.GetCustomAttribute(typeof(MyInterfaceCheckAttribute), true) as MyInterfaceCheckAttribute;
if (myAtt != null)
{
typesToCheck.Add(typeToCheck, myAtt);
}
}
foreach (Type typeToCheck in Assembly.GetExecutingAssembly().GetTypes())
{
Type[] interfaces = typeToCheck.GetInterfaces();
foreach (KeyValuePair<Type, MyInterfaceCheckAttribute> kvp in typesToCheck)
{
if (interfaces.Contains(kvp.Key) && !interfaces.Contains(kvp.Value.TypeThatShouldBeInherited))
{
Assert.Fail("The type " + typeToCheck.Name + " should inherit the interface " + kvp.Value.TypeThatShouldBeInherited.Name);
}
}
}
}
The obvious way would be to have SomeInterface : SomeBaseInterface and have ImplementingClass : SomeInterface, SomeOtherInterface. Can you clarify why it is not a possibility? This forces the class implementing SomeInterface to at least inherit from SomeBaseInterface and this can be extended by additionally by inheriting from SomeOtherInterface.
The only difference is that it's possible to no inherit SomeOtherInterface, but for all you know that interface could contain nothing anyway.
EmptyInterface:
interface SomeOtherOtherInterface : SomeBaseInterface {
}
I would suggest if your wanting to allow the class to inherit from the above interface and not SomeBaseInterface you're doing something wrong. Also the implication is that your specifying for the existence of more unknown methods, which also is a touch suspicious.
Is it that there are things you should have put in SomeBaseInterface but didn't? Is there, for example, a void SendEmail in one derived interface and a void SendFax in another when clearly something like SendMessage should have been in SomeBaseInterface all along?
But obviously, if you want to proceed anyway use the unit testing approach.
Just to make it clear about inheritance and interfaces. Let's assume that we have interfaces IAnimal and IFeline:
interface IAnimal
{
void Eat();
}
interface IFeline: IAnimal
{
void Purr();
}
Now let's define class Cat and require it to implement interface IFeline:
class Cat: IFeline
{
}
Compiling the code:
'Cat' does not implement interface member 'IFeline.Purr()'
'Cat' does not implement interface member 'IAnimal.Eat()'
And now it is clear that compiler expects us to implement both interfaces IAnimal and IFeline in class Cat.

Declaring member function in interface

Firstly I am pretty new to C#. I would like to have an interface declare a member function like in the following piece of code
interface IMyInterface {
void MyAction() {
// do stuff depending on the output of function()
}
void Function();
}
here Function is pure virtual and should be implemented by children of IMyInterface. I could use an abstract class instead of an interface but then I could not inherit from other classes... Say for example that MyAction is recursiverly searching a directory for files and applying Function to any file found to make my example clear.
How to change my design in order to overcome the constraint that interfaces cannot implement classes ?
Edit : In C++ what I would do is using templates as such
template<class A>
static void MyAction(const A& a) {
// do stuff depending on the output of A::Function()
};
class MyClass {
void Function();
};
I was wondering if there were an elegant way to do this using interfaces in C#.
In C# you don't have multiple inheritance. You can circumvent this limitation by using composition.
Define your interface like this (Function needs not to be defined here):
public interface IMyInterface
{
void MyAction();
}
Declare an abstract class with an abstract Function and implementing this interface:
public abstract class MyInterfaceBase : IMyInterface
{
public void MyAction()
{
// Do stuff depending on the output of Function().
Function();
}
protected abstract void Function();
}
From this abstract class you can derive a concrete implementation. This is not yet your "final" class, but it will be used to compose it.
public class ConcreteMyInterface : MyInterfaceBase
{
protected override void Function()
{
Console.WriteLine("hello");
}
}
Now let's come to your "final", composed class. It will derive from SomeBaseClass and implement IMyInterface by integrating the functionality of ConcreteMyInterface:
public class SomeBaseClass
{
}
public class MyComposedClass : SomeBaseClass, IMyInterface
{
private readonly IMyInterface _myInterface = new ConcreteMyInterface();
public void MyAction()
{
_myInterface.MyAction();
}
}
UPDATE
In C# you can declare local classes. This comes even closer to multiple inheritance, as you can derive everything within your composing class.
public class MyComposedClass : SomeBaseClass, IMyInterface
{
private readonly IMyInterface _myInterface = new ConcreteMyInterface();
public void MyAction()
{
_myInterface.MyAction();
}
private class ConcreteMyInterface : MyInterfaceBase
{
protected override void Function()
{
Console.WriteLine("hello");
}
}
}
The only way to directly handle this would be to use an abstract class, as the interface cannot contain "logic" of any form, and is merely a contract.
One alternative, however, would be to make an interface and a static class. You could then place your logic in an extension method using the interface.
public interface IMyInterface {
void Function();
}
public static class MyInterfaceExtensions {
public static void MyAction(this IMyInterface object)
{
// use object.Function() as needed
}
}
The main disadvantages here are more types, which reduces maintainability, and a lack of discoverability.
You can define MyAction as extension method:
public interface IMyInterface
{
void Function();
}
public static class MyInterfaceExtensions
{
public static void MyAction(this IMyInterface obj)
{
obj.Function();
}
}
Example:
public class HelloWorld : IMyInterface
{
public void Function()
{
Console.WriteLine("Hello World");
}
public static void Main(string[] args)
{
new HelloWorld().MyAction();
}
}
Output:
Hello World
Interfaces can't implement any behavior they are just contracts. If you want to implement some logic while defining a contract you could use an abstract class.
For that purpose . you need to define abstract class.
You can provide default implementations or you can leave the implementation to the derived class.
If the derived class want to override some thing they can always do that .
This gives them the flexibility to use base along with changes they want to override.
Declare the function's interface (Signature and return types), in an interface,
Then create an abstract class that is defined to implement that interface, and implement a basic default implementation in the abstract class. Then, create other concrete classes that inherit from the abstract class, but when necessary, override the abstract classes base implementation with different implementation.
This sort of problem might best be overcome by separating the external behaviours; MyAction in this case, from the internal implementation; MyFunction.
The point here is understanding what should be part of the interface/contract between this class and others, and what should be part of the implementation of that contract.
Here, the contract between this object and its consumers is defined;
interface IMyInterface
{
void MyAction();
}
Now, a base class which implements this interface, and also enforces a particular behaviour;
abstract class BaseClass : IMyInterface
{
public void MyAction()
{
// do some commmon action
// call derived implementation to deal with the outcome
}
protected abstract void MyFunction();
}
And finally, a concrete implementation which deals with the results of MyFunction in some specific way;
class ConcreteClass : BaseClass
{
protected override void MyFunction()
{
// concrete implementation here
}
}
An interface is a contract, and cannot contain implementation.
From your statement above:
I could use an abstract class instead of an interface but then I could not inherit from other classes
I believe you are hitting the "why does C# not support multiple inheritance" question.
Here is a CodeProject Article on Simulated Multiple Inheritance for C#. You should be able to follow this pattern to achieve a workaround to the simple inheritance model of C#.
This is a proposed feature for C# 8.0:
interface IA
{
void M() { WriteLine("IA.M"); }
}
class C : IA { } // OK
IA i = new C();
i.M(); // prints "IA.M"`
https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md

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

Why does overriding a method only occur after I implement an interface?

I've been reading through the book Working Effectively with Legacy Code and I've been playing around with the concept of overriding difficult to test methods in unit tests via the creation of a fake. I put together an example of what I thought would work and it ended up behaving differently than I had been expecting. I think I've just discovered a hole in my understanding of how inheritance and method overloading works in C# and I was wondering if someone could help me understand what's going on here.
I've got the following interface:
public interface IAnimal
{
void MakeSound();
void Move();
}
I then create an implementation of the animal interface as follows:
public class Dog : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Woof");
}
public void Move()
{
Console.WriteLine("Moved");
}
}
When I use this class as follows:
IAnimal myanimal = new Dog();
myanimal.MakeSound();
myanimal.Move();
I get the following output:
Woof
Moved
Now, lets pretend that I'm needing to unit test the Dog class but one of the methods, MakeSound(), needs to be overridden because it is making the class difficult to test for some reason.
I create a fake dog by extending the Dog class and creating a method for MakeSound
public class FakeDog : Dog
{
public void MakeSound()
{
Console.WriteLine("Bark");
}
}
When I use this class as follows:
IAnimal myanimal = new FakeDog();
myanimal.MakeSound();
myanimal.Move();
I get the following output:
Woof
Moved
I had been expecting it to have been:
Bark
Moved
However, if I then have the FakeDog class implement the animal interface and use it:
public class FakeDog : Dog, IAnimal
{
public void MakeSound()
{
Console.WriteLine("Bark");
}
}
I get the following output:
Bark
Moved
I'm just wanting to understand the reason why this now overrides the method as I had been expecting when I had just been extended the Dog class. Can anyone set me straight on this?
In the first case you're creating a new method which hides the original implementation of IAnimal.MakeSound. You should have seen a warning suggesting that you use the new keyword to make this explicit.
In the second case you're re-implementing IAnimal. Implementing an interface doesn't require the override keyword (although it might have been nice if the language designers had required that).
To avoid re-implementing the interface, you could make MakeSound virtual in Dog, and then explicitly override it in FakeDog. At that point there's only one possible resolution involved, and everything is simpler to understand. I try to avoid reimplementation and method hiding whenever possible.
(Sorry for answering with a question, but you might genuinely find this experiment informative) What happens when you implement dog as follows:
public class Dog : IAnimal
{
public virtual void MakeSound()
{
Console.WriteLine("Woof");
}
//...
Note the "virtual"
You need to declare the MakeSound method as virtual in the Dog class and override it in the FakeDog class:
public class Dog : IAnimal
{
public virtual void MakeSound()
{
Console.WriteLine("Woof");
}
public virtual void Move()
{
Console.WriteLine("Moved");
}
}
public class FakeDog : Dog
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}

Categories