In this course project, the teacher created an abstract base class (EfEntityRepositoryBase) for data access, a concrete class for each entity (ProductDal) that inherits abstract base class and implements an interface (IEntityRepository). ProductDal also has its interface (IProductDal) which also implements IEntityRepository.
What is the use case for doing it? I can't understand the point of IProductDal implementing IEntityRepository, since ProductDal already inherits the abstract base class that implements the same interface. So if any function updates in IEntityRepository, should be no problem. If someone can explain so would be great. Below abstract class and interfaces code.
public class ProductDal : EfEntityRepositoryBase<Product>, IProductDal{ }
public interface IEntityRepository<T>
{
void Add(T entity);
void Delete(T entity);
void Update(T entity);
List<T> GetAll(Expression<Func<T, bool>> expression = null);
T GetById(Expression<Func<T, bool>> expression);
}
public interface IProductDal: IEntityRepository<Product>
{
}
public class EfEntityRepositoryBase<TEntity> : IEntityRepository<TEntity> where TEntity : class, IEntity, new()
{
public void Add(TEntity entity)
{
using (BookStoreTrackerDBContext context = new BookStoreTrackerDBContext())
{
var addedEntity = context.Entry(entity);
addedEntity.State = EntityState.Added;
context.SaveChanges();
}
}
}
I think it is easy to understand that you feel, when looking at your provided example, tempted to call out the IProductDal interface as being redundant. In fact, it doesn't add any extra members to the type ProductDal because the interface IProductDal and the generic class EfEntityRepositoryBase are defined with the same generic parameter type Product. Since those teaching examples are not set in context of real application code, their real intentions or ideas behind them are not easy to understand.
As a side note, you should know that in case the class EfEntityRepositoryBase<TEntity> would be defined with a different generic parameter type than Product e.g., int, ProductDal would have two implementations/member overloads of the IEntityRepository<T> interface.
For example:
public class ProductDal : EfEntityRepositoryBase<int>, IProductDal
{
// Implementation of IProductDal. The EfEntityRepositoryBase type provides another 'int' overload
public void Add(Product entity) {}
}
void Main()
{
var productDal = new ProductDal();
// Implementation of IEntityRepository<int> provided by class EfEntityRepositoryBase<int>
productDal.Add(6);
// Implementation of 'IProductDal' (provided by class 'ProductDal')
productDal.Add(new Product());
}
You can see that your provided example shows a special case where the EfEntityRepositoryBase<TEntity> already provides the implementation for the IEntityRepository<Product> and the IProductDal interfaces.
Back to your example: if you make use of type casting, you will find another use case for having the alledgedly redundant type definitions:
Given is your ProductDal type with the following class signature
public class ProductDal : EfEntityRepositoryBase<int>, IProductDal
You have now multiple types available to access the implementation of IEntityRepository<Product>
void Main()
{
// Create an instance of ProducDal
ProductDal productDal = new ProductDal();
/* Use the instance of ProductDal with multiple overloads
to show implicit type casting */
UseProductDal(productDal);
UseIProductDal(productDal);
UseIEntityRepository(productDal);
UseEntityRepository(productDal);
}
void UseProductDal(ProductDal productDal)
{
// Instantiate the argument
var product = new Product();
productDal.Add(product);
}
void UseIProductDal(IProductDal productDal)
{
// Instantiate the argument
var product = new Product();
productDal.Add(product);
}
void UseIEntityRepository(IEntityRepository<Product> productDal)
{
// Instantiate the argument
var product = new Product();
productDal.Add(product);
}
void UseEntityRepositoryBase(EntityRepositoryBase<Product> productDal)
{
// Instantiate the argument
var product = new Product();
productDal.Add(product);
}
This shows how to make use of the implicit type casting and also how to use interfaces.
You now see that although EntityRepositoryBase<Product> already implements IEntityRepository<Product>, still having ProductDal additionally implement the IProductDal interface makes perfect sense in order to enable ProductDal to be used where only the IProductDal interface is known.
You can make use of interface casting to hide members. For example if you add exclusive members to each interface then this members are only accessible when casting the implementor to the corresponding interface:
public interface IEntityRepository<T>
{
void Add(T entity);
}
public interface IProductDal: IEntityRepository<Product>
{
// Exclusive member. Will be only visible when accessed through this interface.
int GetProductCount();
}
Given is your ProductDal type with the following class signature
public class ProductDal : IEfEntityRepository<int>, IProductDal
void Main()
{
// Create an instance of ProducDal
ProductDal productDal = new ProductDal();
/* Use the instance of ProductDal with multiple overloads
to show implicit type casting */
UseProductDal(productDal);
UseIProductDal(productDal);
UseIEntityRepository(productDal);
UseEntityRepository(productDal);
}
// All implemented interfaces are visible since there is no casting involved.
// All members are referenced via the implementor type ProductDal.
void UseProductDal(ProductDal productDal)
{
// Instantiate the argument
var product = new Product();
productDal.Add(product);
int productCount = productDal.getProductCount();
}
// Only 'IProductDal' is visible since there is an implicit cast to an interface type involved
void UseIProductDal(IProductDal productDal)
{
// Instantiate the argument
var product = new Product();
// 'Add()' is provided by 'IEntityRepository<T>',
// which is implemented by 'IProductDal' and therefore "visible"
productDal.Add(product);
// 'GetProductCount()' is provided by 'IProductDal'
int productCount = productDal.GetProductCount();
}
// Only 'IEntityRepository<T>' is visible since there is an implicit cast to the interface type
void UseIEntityRepository(IEntityRepository<Product> productDal)
{
// Instantiate the argument
var product = new Product();
productDal.Add(product);
// 'GetProductCount()' is only available via the 'IProductDal' interface.
// It's not visible here.
//int productCount = productDal.GetProductCount();
}
At the root of this question is how interfaces are used in dependency injection and mocking / unit testing.
Let's look at what each of these classes and interfaces give you...
ProductDal
This class contains the logic for interacting with Product instances held in your data store.
IProductDal
Where you want to use a ProductDal to interact with Product instances in your data store, declaring it as a IProductDal instead allows your unit tests for code which is dependent on ProductDal to create mock instances of IProductDal which behave however is needed for your unit tests, so that your unit tests for code which uses ProductDal aren't dependent on an actual database. In your production code you can use dependency injection to inject a real ProductDal where an IProductDal is declared.
IEntityRepository
This looks like a fairly generic interface specifying some basic CRUD operations which might be useful for any entity which you might hold in a data store, and it's agnostic of what the type of data store is (e.g. SQL server / MongoDB / Cassandra / imp with a filing cabinet full of notebooks) or what Object Relational Mapper (e.g. Entity Framework / NHibernate) you might be using to access the data store.
EfEntityRepositoryBase
This abstract class contains an implementation of the basic CRUD methods in IEntityRepository which is specific to Entity Framework, to save you repeating those methods in your ProductDal etc classes. You could have another abstract class with implementations of those methods for another ORM (e.g. NHibernate), and if you were to switch from using Entity Framework to using NHibernate then you'd just need to change the inheritance of each of your ProductDal etc classes so that they derive from NHibernateEntityRepository<T> rather than EfEntityRepositoryBase<T>.
But back to the question...
I can't understand the point of IProductDal implementing IEntityRepository, since ProductDal already inherits the abstract base class that implements the same interface
If you're using ProductDal rather than IProductDal wherever you want to interact with Product instances in your data store, then it doesn't really make any difference in your production code, but your unit tests are going to be really difficult to write, and probably slow to run and rather flaky too, because they'll depend on a real data store which is in exactly the right state at the start of each test case.
If instead you're using IProductDal to interact with Product instances in your data store, and using dependency injection to use a ProductDal where a IProductDal is needed by your production code (so that unit tests for that code aren't dependent on a real data store), you'll hit a different problem. Consider this unit test (which uses the Moq mocking framework, but the same issue exists regardless of what mocking framework you use):
[Fact]
public void Test1()
{
var mockProductDal = new Mock<IProductDal>();
mockProductDal.Setup(m => m.GetAll(null))
.Returns(new List<Product> { new Product { } });
}
In the above test, the compiler only understands m => m.GetAll if IProductDal is derived from EfEntityRepositoryBase (which is where the GetAll method is defined).
Similar problems will also turn up in any of your production code which uses IProductDal - after all, that code is a consumer of IProductDal / ProductDal in the same way that the above unit test is.
In short...
Reference the interface rather than the implementation in your production code. Use dependency injection in your production code to inject the real implementation, and mock the interface in your unit tests to remove dependencies on external resources such as data stores. If you do this then you also need to do apparently strange things like making Interface1 implement Interface2 when the class which implements Interface1 is derived from a class which implements Interface2. But it'll make your unit tests easier to write, and better, and better unit tests can only be a good thing.
Related
We have an interface to deal with DAL with pretty simple definition:
interface IRepository<T> : IQueriable<T> // so we can read data from database
{
Save(T document); // dozen of methods here
}
Mostly we use two implementations: real version and in memory version for unit testing. Here is declarations of one of class:
public RealRepository : IRepository<AccountEntity> { ... }
// typical IOC usage
services.AddSingleton<IRepository<AccountEntity>, RealRepository<AccountEntity>>();
Now we are working to spin off for main codebase to custom version of project and we need custom fields in data and occassional custom behavior in repository. Most of classes are fine with base implementation but others would require specific implementation. So my goal is to get to following services in:
var repository = new RealRepository<CustomAccountEntity>();
services.AddSingleton(IRepository<AccountEntity>, repository);
// for new classes
services.AddSingleton(IRepository<CustomAccountEntity>, repository);
I tried to add out T to IRepository but I am using T in input parameters and this gave compile time "Invalid variance" error.
I can see a solution by adding second type parameter to interface so it looks like:
IRepository<TBase, out TChild> : IQueriable<TChild> {
Save (T document);
}
Finally, Question: How can make change 100% backward compatible?
What I tried:
Add IRepository<T>: IRepository<T,T> -> complies, but RealRepository is not implementing IRepository anymore.
Add 2 interfaces in implementation: public class RealRepository<TBase, TChild>: IRepository<TBase, TChild>, IRepository<TChild> but this gives compliation error 'cannot implement both ... and ... because they may unify for some type parameter substitutions'
Save(T document) has T in a contravariant position. That means in T, not out T.
Let's recap what contravariance means. Suppose you had this code:
using System;
public class Entity {}
public class AccountEntity : Entity {}
public class CustomAccountEntity : AccountEntity {}
public interface IQueryable<in T>
where T : Entity
{}
public interface IRepository<in T>
where T : Entity
{
void Save(T record);
}
public class EntityRepository<T> : IRepository<T>
where T : Entity
{
public void Save(T record) {}
}
public class Program
{
public static void Main()
{
// This is ***VALID***:
IRepository<CustomAccountEntity> repo = new EntityRepository<AccountEntity>();
Console.WriteLine(repo == null ? "cast is invalid" : "cast is valid");
}
}
https://dotnetfiddle.net/cnEdcm
So whenever you need a IRepository<CustomAccountEntity>, you can use a concrete EntityRepository<AccountEntity> instance. Seems counter-intuitive, but it's actually totally right: If the concrete method is Save(AccountEntity), it can obviously handle CustomAccountEntity instances too; OTOH if the concrete method were Save(CustomAccountEntity), it would NOT be able to handle simple AccountEntity instances.
Having said that, then I think you should
Use contravariance instead;
Declare all dependencies using the most specialised type, e.g. IRepository<CustomWhateverEntity>;
In the IoC registration code, for each particular entity, setup either Repository<CustomeWhateverEntity>, if you need the extra behaviour, or just Repository<WhateverEntity> otherwise.
I have a large legacy WPF project that I'm now trying to get unit tested with NUnit (v. 2.6.3) and Moq (v. 4.2), but I'm having trouble with mocking certain classes. There's one in particular, a control class derived from System.Windows.Forms.Integration.WindowsFormsHost, that's needed all over the project and has a lot of external dependencies, so it's very important to be able to mock it.
Let's call that class Foo, and here's the test case:
[TestFixture,RequiresSTA]
public class TestMainWindowViewModel {
[Test]
public void Test1() {
var mockRepository = new MockRepository(MockBehavior.Loose) { DefaultValue = DefaultValue.Empty };
var mockFoo = mockRepository.Create<Foo>();
var sut = new MainWindowViewModel(mockFoo.Object);
}
}
My problem is that for some weird reason, while evaluating parameter mockFoo.Object in the last line, we go straight inside the constructor of the concrete class Foo! I have confirmed that this really happens with debugger, and also, the test run crashes with an error of not finding the DLL's the concrete implementation depends on.
Any ideas what could be causing this? As far as I understand, there should be NO connection to the concrete implementation here!
Thanks in advance for any advice!
-Seppo
Any ideas what could be causing this? As far as I understand, there should be NO connection to the concrete implementation here!
Moq creates its objects (mocks) by deriving from concrete implementation (your case) or implementing interface (typical, more common case):
// implement interface
var mock1 = new Mock<IService>();
// derive from ServiceImplementation
var mock2 = new Mock<ServiceImplementation>();
This is how underlying mechanisms work -- in order to create mock, Moq will have to dynamically create new type representing that mock, either by implementing interface or deriving from base class. Which means your Foo constructor should and is executed. This is how it works.
Since this is legacy code class (Foo) I suggest wrapping it with new, mockable interface and make your code depend on this interface instead:
interface IFoo
{
void DoFoo();
}
class FooWrapper : IFoo
{
private readonly Foo legacyFoo;
public FooWrapper(Foo legacyFoo)
{
this.legacyFoo = legacyFoo;
}
public void DoFoo()
{
legacyFoo.DoFoo();
}
}
Your new (non-legacy) code should depend on IFoo, not Foo and you'll be good to go.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interfaces: Why can't I seem to grasp them?
to work with a library I just found I need to implement a few interfaces first. But some methods seem to be asking for objects that have the type of some interfaces...
And if I have an interface called MyInterface I can write things like :
MyInterface shoe;
It does not really make sense to me. Can somebody teach me this concept ?
I read this : http://www.dotnetperls.com/interface but it did not really help, I think this concept is a bit more complex than what is presented here.
Thanks !
edit :
For those who wonder, I am not new to Interfaces but it is the first time I ran into such a use of them. And for those downgrading my question, I did search but was unlucky apparently.
A simple explanation: A class is like a company. If it claims to be a sales company, it has to provide sales services. It it claims to be a train factory, it has to be able to make trains.
If the national railroads wants to buy trains, it can use any company that can produce trains.
An interface describes what a class has to be able to do. It is like a contract. Each class that wants to have an interface has to fulfill that contract and be able to do what the contract says it has to do. Class instances can perform actions through class methods.
However, the contract doesn't say how the class should do it. So a class can implement the functionality however it wants, or in other words, implement the interface.
public Train
{
private price;
public Train(float price) { this.price = price; }
}
public IMyInterface
{
Train MakeTrain();
}
public ExpensiveTrainFactory : ITrainProducer
{
// make a luxury, expensive train
public Train MakeTrain() { return new Train(4000.0); }
}
public CheapTrainFactory : ITrainProducer
{
// make a cheap train
public Train MakeTrain() { return new Train(500.0); }
}
public NationalRailways
{
List<Train> trains;
public NationalRailways()
{
this.trains = new List<Train>();
}
public Train BuyTrain(ITrainProducer factory)
{
// you can call MakeTrain() because the ITrainProducer guarantees that it can make trains
trains.Add(factory.MakeTrain());
}
}
and then in your code:
NationalRailways railway = new NationalRailways();
ExpensiveTrainFactory expFactory = new ExpensiveTrainFactory();
CheapTrainFactory cheapFactory = new CheapTrainFactory();
// expFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer)
railways.BuyTrain(expFactory);
// cheapFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer) as well
railways.BuyTrain(cheapFactory);
You can declare an Interface, like in your example. However you can not instantiate one.
MyInterface shoe = new MyInterface ();
The above is not legal code. Since an Interface just describes a contract, it has no implementation details, this is left to the client code (you). Therefore it makes no sense to be able to create actual instances of MyInterface.
What you can do, is have a class SomeClass, implement the MyInterface contract:
SomeClass: MyInterface
{
//implement the methods of MyInterface. All of them, to fulfill the contract.
}
Then you can do things like:
MyInterface shoe = new SomeClass();
Since SomeClass implements the MyInterface contract, the above is legal. You can create an instance of SomeClass because it contains implementation details.
Then you can build on this and create more classes which implement MyInterface.
The beauty of this is that you can have a method for example:
void someMethod (MyInterface test)
{
}
You can pass this method the SomeClass object or any other class you created which implements MyInterface.
Then inside this method, you can call methods that the contract contains without knowing the exact object which has been passed to you. This makes writing future code easier. You can create new objects and so long as they implement MyInterface, it is valid to pass this object to someMethod without changing the declaration of the method.
You are correct, you can't directly create an instance of an interface. However, you can create an instance of some type that implements that interface.
Say I have an interface
public IMyInterface
{
void DoSomething();
}
(note: usually you start the name of an interface with "I")
Plus I have a class
public MyClass: IMyInterface
{
public void DoSomething() { ... }
}
Then I can do
IMyInterface something = new MyClass();
although you often call some (factory) method to return some class that implements that interface instead of directly doing a new.
By using the interface as the type of your variable, you specify that you are only interested in the methods and properties specified there.
In C#, each value has two different types: apparent type and actual type. The apparent type is the type of the variable holding the value, and the actual type comes from the constructor used to create the value. Let's say we have the following class:
class MyClass : BaseClass, IMyInterface {
/* ... */
}
Then all the following declarations are valid:
object obj1 = new MyClass();
IMyInterface obj2 = new MyClass();
BaseClass obj3 = new MyClass();
MyClass obj4 = new MyClass();
The apparent and actual types are as follows:
object obj1 = new MyClass(); /* apparent: object, actual: MyClass */
IMyInterface obj2 = new MyClass(); /* apparent: IMyInterface, actual: MyClass */
BaseClass obj3 = new MyClass(); /* apparent: BaseClass, actual: MyClass */
MyClass obj4 = new MyClass(); /* apparent: MyClass, actual: MyClass */
When you manipulate an object (call its methods, etc), you do it assuming the object has its apparent type - you can't call any class-specific methods of an object. The apparent type dictates the interface of the object visible outside the object.
What actually happens under the hood is done according to the object's actual type - for example, if you override the ToString method of your class, the overridden method is called in the following code:
object obj = new MyClass();
Console.WriteLine(obj.ToString());
The actual type dictates how the object's functionality is implemented.
Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me use same example as per your link with bit of modification:
using System;
interface IPerl
{
void Read();
}
class Test : IPerl
{
public void Read()
{
Console.WriteLine("Read Test");
}
}
class Test1 : IPerl
{
public void Read()
{
Console.WriteLine("Read Test1");
}
}
class Program
{
static void Main()
{
IPerl perl = new Test(); // Create instance of Test.
perl.Read(); // Call method on interface output will be different then Test1.
perl = new Test1(); // Create instance of Test1.
perl.Read(); // Call method on interface output will be different then Test.
}
}
Output:
"Read Test"
"Read Test1"
I hope this would help.
Thanks Ankur
What Interfaces Are
Interfaces basically define a blueprint for a class or a struct. The programmed definition of an interface looks very similar to a class, but nothing is implemented. Interfaces define the properties, methods, events, and indexers, but the interface does not define the implementation of any of these. It just declares their existence. Interfaces will not actually define any functionality. They just define ways in which interactions with a class takes place.
What Interfaces Are Not
Interfaces should not be confused with inheritance. They are two very different things. Inheritance will define a lot of the implementation and is used for code reuse. Interfaces are merely a definition for how communication with the implementing classes must take place. It is like a written contract. A class "signing" the contract will agree to perform certain specified actions in any way it wishes, but it must perform the specified actions.
When to Use Interfaces
Interfaces allow us to create nice layouts for what a class is going to implement. Because of the guarantee the interface gives us, when many components use the same interface it allows us to easily interchange one component for another which is using the same interface. Dynamic programs begin to form easily from this.
For more information visit this post about Understanding_Interfaces_in_C#
I'm playing around with Domain Driven Development. I'm using a generic repository implementation that is defined as follows: (this is implemented as Repository<T>)
public interface IRepository<T> where T : class, IEventSource, new()
{
T FindByKey(Guid key);
IEnumerable<T> FindByQuery(Predicate<T> filter);
IEnumerable<T> GetAll();
T CreateObject();
}
Let's say I have an Order class, that cannot be created without a Customer parameter. I'm using CreateObject to set the Key of the entity with a sequential Guid generator.
What is the solution that minimizes development time and coupling?
Currently I have a parameterless constructor, and am calling some
Initialize(Customer) method.
I could create a ICustomerRepository, but that would mean there is a
lot of extra development time per entity.
I can also modify CreateObject to take params object[] args, but that is not type safe at compile time.
I could remove CreateObject and use constructors to create the object, but that means I need to have access to the the Guid generation algorithm everywhere I instantiate an object, increasing coupling.
In a base class for an entity I could set the key in the constructor, reducing coupling, but requiring some static reference to the algorithm.
Update
I've implemented the strategy following sll's answer. The new signature for the repository is now:
public interface IRepository<T> where T : class, IEventSource
{
T FindByKey(Guid key);
IEnumerable<T> FindByQuery(Func<T, bool> predicate);
IEnumerable<T> GetAll();
T CreateObject();
T CreateObject(IConstructorParameters parameters);
}
The parameterless CreateObject creates an instance by attempting to call the parameterless constructor (using IL Emit for performance).
The second CreateObject attempts to create a method that calls the constructor where the properties on the IConstructorParameters match a constructor on the Entity object.
Implementation:
private Dictionary<Type, Func<IConstructorParameters, T>> _constructionMethods
= new Dictionary<Type, Func<IConstructorParameters, T>>();
public T CreateObject(IConstructorParameters args)
{
T newObject;
if (args == null)
{
args = ConstructorParameters.Empty;
}
Type paramType = args.GetType();
Func<IConstructorParameters, T> constructor;
if (!_constructionMethods.TryGetValue(paramType, out constructor))
{
//Emit IL to create a Func<IConstructorParameters,T>
constructor = CreateConstructor(paramType);
_constructionMethods.Add(paramType, constructor);
}
newObject = constructor(args);
newObject.Key = _guidCreator.Generate();
return newObject;
}
Some points as suggestion, i would do as follows.
Keep IRepository generic, and also create specific interfaces containing the contract only with what is relevant to the entity, ICustomerRepository as your example.
Remove the guid generation to a service class, since this task is most relevant for the infrastructure and not domain.
If you do not want implement IOrderRepository - you can abstract CreateObject() method parameters by an interface like IConstructionParameters and then for each entity implement concrete parameters like OrderConstructionParameters.
This approach also known as Parameter Object design pattern which design rationale - more decoupled system design.
public interface IRepository<T>
{
T CreateObject(IConstructionParameters parameters);
}
public sealed class OrderConstructionParameters : IConstructionParameters
{
public Customer Customer
{
get;
private set;
}
}
I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don't understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
MyNiftyClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something nifty
}
}
MyOddClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something odd
}
}
And now you have:
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
public void ThisMethodShowsHowItWorks(IMyInterface someObject)
{
someObject.CallSomeMethod();
}
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
public void AnotherClass()
{
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
// Pass in the nifty class to do something nifty
this.ThisMethodShowsHowItWorks(nifty);
// Pass in the odd class to do something odd
this.ThisMethodShowsHowItWorks(odd);
}
EDIT
This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?
That is, why use:
IMyInterface foo = new MyConcreteClass();
in preference to:
MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
public void AMethod()
{
// Why use this?
IMyInterface foo = new MyConcreteClass();
// Why not use this?
MyConcreteClass bar = new MyConcreteClass();
}
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
I typically inject dependencies so the polymorphism is needed
Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this:
public void AMethod(string input)
{
IMyInterface foo;
if (input == "nifty")
{
foo = new MyNiftyClass();
}
else
{
foo = new MyOddClass();
}
foo.CallSomeMethod();
}
Because this:
public void ReadItemsList(List<string> items);
public void ReadItemsArray(string[] items);
can become this:
public void ReadItems(IEnumerable<string> items);
Edit
Think of it like this:
You have to be able to do this.
rather than:
You have to be this.
Essentially this is a contract between the method and it's callers.
Using interface variables is the ONLY way to allow handler methods to be written which can accept data from objects that have different base classes.
This is about as clear as anyone is going to get.
An interface is used so you do not need to worry about what class implements the interface. An example of this being useful is when you have a factory method that returns a concrete implementation that may be different depending on the environment you are running in. It also allows an API designer to define the API while allowing 3rd parties to implement the API in any way they see fit. Sun does this with it's cryptographic API's for Java.
public interface Foo {
}
public class FooFactory {
public static Foo getInstance() {
if(os == 'Windows') return new WinFoo();
else if(os == 'OS X') return new MacFoo();
else return new GenricFoo();
}
}
Your code that uses the factory only needs to know about Foo, not any of the specific implementations.
I was in same position and took me few days to figure out why do we have to use interface variable.
IDepartments rep = new DepartmentsImpl();
why not
DepartmentsImpl rep = new DepartmentsImpl();
Imagine If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.
class Test
{
static void Main()
{
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
// The following lines all call the same method.
sc.Paint();
ctrl.Paint();
srfc.Paint();
}
}
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
IControl c = new SampleClass();
ISurface s = new SampleClass();
s.Paint();
Please do correct me if i am wrong as i am still learning this Interface concept.
Lets say you have class Boat, Car, Truck, Plane.
These all share a common method TakeMeThere(string destination)
You would have an interface:
public interface ITransportation
{
public void TakeMeThere(string destination);
}
then your class:
public class Boat : ITransportation
{
public void TakeMeThere(string destination) // From ITransportation
{
Console.WriteLine("Going to " + destination);
}
}
What you're saying here, is that my class Boat will do everything ITransportation has told me too.
And then when you want to make software for a transport company. You could have a method
Void ProvideServiceForClient(ITransportation transportationMethod, string whereTheyWantToGo)
{
transportationMethod.TakeMeThere(whereTheyWantToGo); // Cause ITransportation has this method
}
So it doesn't matter which type of transportation they want, because we know it can TakeMeThere
This is not specific to C#,so i recommend to move to some othere flag.
for your question,
the main reason why we opt for interface is to provide a protocol between two components(can be a dll,jar or any othere component).
Please refer below
public class TestClass
{
static void Main()
{
IMyInterface ob1, obj2;
ob1 = getIMyInterfaceObj();
obj2 = getIMyInterfaceObj();
Console.WriteLine(ob1.CallSomeMethod());
Console.WriteLine(obj2.CallSomeMethod());
Console.ReadLine();
}
private static bool isfirstTime = true;
private static IMyInterface getIMyInterfaceObj()
{
if (isfirstTime)
{
isfirstTime = false;
return new ImplementingClass1();
}
else
{
return new ImplementingClass2();
}
}
}
public class ImplementingClass1 : IMyInterface
{
public ImplementingClass1()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return true;
}
#endregion
}
public class ImplementingClass2 : IMyInterface
{
public ImplementingClass2()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return false;
}
#endregion
}
public interface IMyInterface
{
bool CallSomeMethod();
}
Here the main method does not know about the classes still it is able to get different behaviour using the interface.
The purpose of the Interface is to define a contract between several objects, independent of specific implementation.
So you would usually use it when you have an Intrace ISomething, and a specific implementation
class Something : ISomething
So the Interface varialbe would come to use when you instantiate a contract:
ISomething myObj = new Something();
myObj.SomeFunc();
You should also read interface C#
Update:
I will explaing the logic of using an Interface for the variable and not the class itself by a (real life) example:
I have a generic repositor interace:
Interface IRepository {
void Create();
void Update();
}
And i have 2 seperate implementations:
class RepositoryFile : interface IRepository {}
class RepositoryDB : interface IRepository {}
Each class has an entirely different internal implementation.
Now i have another object, a Logger, that uses an already instansiated repository to do his writing. This object, doesn't care how the Repository is implemented, so he just implements:
void WriteLog(string Log, IRepository oRep);
BTW, this can also be implemented by using standard classes inheritance. But the difference between using interfaces and classes inheritance is another discussion.
For a slightly more details discussion on the difference between abstract classes and interfaces see here.
Say, for example, you have two classes: Book and Newspaper. You can read each of these, but it wouldn't really make sense for these two to inherit from a common superclass. So they will both implement the IReadable interface:
public interface IReadable
{
public void Read();
}
Now say you're writing an application that will read books and newspapers for the user. The user can select a book or newspaper from a list, and that item will be read to the user.
The method in your application that reads to the user will take this Book or Newspaper as a parameter. This might look like this in code:
public static void ReadItem(IReadable item)
{
item.Read();
}
Since the parameter is an IReadable, we know that the object has the method Read(), thus we call it to read it to the user. It doesn't matter whether this is a Book, Newspaper, or anything else that implements IReadable. The individual classes implement exactly how each item will be read by implementing the Read() method, since it will most likely be different for the different classes.
Book's Read() might look like this:
public void Read()
{
this.Open();
this.TurnToPage(1);
while(!this.AtLastPage)
{
ReadText(this.CurrentPage.Text);
this.TurnPage();
}
this.Close();
}
Newspaper's Read() would likely be a little different:
public void Read()
{
while(!this.OnBackPage)
{
foreach(Article article in this.CurrentPage.Articles)
{
ReadText(article.Text);
}
}
}
The point is that the object contained by a variable that is an interface type is guaranteed to have a specific set of methods on it, even if the possible classes of the object are not related in any other way. This allows you to write code that will apply to a variety of classes that have common operations that can be performed on them.
No, it is not possible. Designers did not provide a way. Of course, it is of common sense also. Because interface contains only abstract methods and as abstract methods do not have a body (of implementation code), we cannot create an object..
Suppose even if it is permitted, what is the use. Calling the abstract method with object does not yield any purpose as no output. No functionality to abstract methods.
Then, what is the use of interfaces in Java design and coding. They can be used as prototypes from which you can develop new classes easily. They work like templates for other classes that implement interface just like a blue print to construct a building.
I believe everyone is answering the polymorphic reason for using an interface and David Hall touches on partially why you would reference it as an interface instead of the actual object name. Of course, being limited to the interface members etc is helpful but the another answer is dependency injection / instantiation.
When you engineer your application it is typically cleaner, easier to manage, and more flexible if you do so utilizing dependency injection. It feels backwards at first if you've never done it but when you start backtracking you'll wish you had.
Dependency injection normally works by allowing a class to instantiate and control the dependencies and you just rely on the interface of the object you need.
Example:
Layer the application first. Tier 1 logic, tier 2 interface, tier 3 dependency injection. (Everyone has their own way, this is just for show).
In the logic layer you reference the interfaces and dependency layer and then finally you create logic based on only the interfaces of foreign objects.
Here we go:
public IEmployee GetEmployee(string id)
{
IEmployee emp = di.GetInstance<List<IEmployee>>().Where(e => e.Id == id).FirstOrDefault();
emp?.LastAccessTimeStamp = DateTime.Now;
return emp;
}
Notice above how we use di.GetInstance to get an object from our dependency. Our code in that tier will never know or care about the Employee object. In fact if it changes in other code it will never affect us here. If the interface of IEmployee changes then we may need to make code changes.
The point is, IEmployee emp = never really knows what the actual object is but does know the interface and how to work with it. With that in mind, this is when you want to use an interface as opposed to an object becase we never know or have access to the object.
This is summarized.. Hopefully it helps.
This is a fundamental concept in object-oriented programming -- polymorphism. (wikipedia)
The short answer is that by using the interface in Class A, you can give Class A any implementation of IMyInterface.
This is also a form of loose coupling (wikipedia) -- where you have many classes, but they do not rely explicitly on one another -- only on an abstract notion of the set of properties and methods that they provide (the interface).