I am trying to create an object that can call one of 3 methods in response to user input. Let's call them, DoShape, DoColor, and DoPowerTool. These methods exist as part of a base class and interfaces respectively:
Public Class PowerTool
{
...
public virtual void DoPowerTool()
{
...
}
}
Public Interface Shape
{
void DoShape(PowerTool p);
}
Public Interface Color
{
void DoColor(PowerTool p);
}
As DoShape and DoColor require a PowerTool, the intuitive thing would be to somehow bake those methods into the PowerTool instance itself.
Unfortunately, I can't have the PowerTool class implement Shape and Color directly, since I won't know until runtime if it's a Red Square Jackahmmer or a Green Ovoid one.
I've dabbled with C#'s delegates, and have a feeling that they might be useful in this case, but I'm not familiar enough to know how to implement them in this precise scenario, and I'm unsure if they're the right choice to give me the modular behavior I'm looking for. (I may be spoiled by Javascript in this regard, where you can simply overwrite functions on objects).
Any thoughts or suggestions on how to continue? I feel like there's probably a very simple solution that I'm overlooking in all this.
A relatively simple way to do what you're talking about (from what I can tell) would be to simply have 3 interfaces:
public interface IPowerTool : IShape, IColor
{
void Execute();
}
Thus, you can simply define:
public RedSquareJackhammer : IPowerTool
{
void DoShape() {}
void DoColor() {}
void Execute() {}
}
Another option is to do this:
public PowerTool
{
IColor color;
IShape shape;
public PowerTool(IColor c, IShape s) {
color = c; share = s;
}
void Execute() {
color.DoColor();
shape.DoShape();
}
}
Then you call it like this:
// JackHammer is derived from PowerTool, Red from IColor, Square from IShape
var redSquareJackhammer = new JackHammer(new Red(), new Square());
Etc.. there are many ways to skin this cat.
I believe what you are referring to is the concept of a Mixin.
This is where one or many implementations for an interface are defined, and then the implementations are reused for their concrete types.
This is unfortunately not really possible in .NET because the framework was desgined without that ability to use multiple inheritance. Though, you may be able to replicate the behavior you're seeking using extension methods or, through dependency injection and the strategy pattern.
If you have any further questions about the patterns, or require more applicable examples, just let me know what you're attempting to accomplish in more detail and I will do my best to help.
If I understand what you are describing, the following strategy pattern may be of benefit:
internal interface IPowerToolStrategy
{
void Execute(PowerTool powerTool);
}
public class RedSquareJackhammer : IShape
{
private readonly IPowerToolStrategy _strategy;
internal RedSquareJackhammer(IPowerToolStrategy strategy)
{
_strategy = strategy;
}
public void DoShape(PowerTool powerTool)
{
_strategy.Execute(powerTool);
}
}
Related
I have a somewhat basic design question that I have not been able to find a good answer to (here, on other forums nor the books I've consulted)
I'm creating a dll and is wondering what the best way to expose its content would be. I'm aiming for a single point of entry for the apps using the dll.
The solution should adhere to the Dependency Inversion Principle (DIP) which would imply the use of an interface. But here is the kicker: the functionality of the dll requires an object to be instantiated and there must only be almost one instance at any time (kinda like a singleton though the thought sends shivers down my spine) It is this fact that I would like to spare the users of the DLL from knowing about.
Some code to explain what I would like to be able to do:
The dll:
namespace MyQuestionableDll
{
interface IMyQuestionableDll
{
public static IMyQuestionableDll Instance; // This is not allowed which makes sense
public void PressTheRedButton();
}
internal class QuestionableImplementation : IMyQuestionableDll
{
public void PressTheRedButton()
{
// Distribute Norwegian Black Metal at local school
}
}
}
And the use case:
using MyQuestionableDll;
class UnluckyAppThatIsForcedToUseQuestionableDlls
{
static void Main(string[] args)
{
IMyQuestionableDll questionableInstance = IMyQuestionableDll.Instance; // Again not allowed which still makes sense
questionableInstance.PressTheRedButton();
// or simply
MyQuestionableDll.Instance.PressTheRedButton();
}
}
An abstract class could be part of the answer but it then starts to feel like not following the DIP anymore.
Any great design insights, knowledge of best practices when making dlls or recommendations regarding Norwegian Black Metal?
If the explanation is too vague I will gladly elaborate on it.
Cheers!
- Jakob
I could imagine a two-factor approach:
A factory interface (that will create/return an instance of ...)
The API interface
For Example:
public interface IMyApiFactory
{
IMyAPI GetInstance();
}
public interface IMyAPI
{
// Whatever your API provides
}
This way you have the complete control inside your dll about how to create and reuse instances (or not).
A similar way would be some kind of Builder-Pattern:
public interface IMyApiBuilder
{
IMyApi Build();
}
public interface IMyApi
{
void PressTheRedButton();
// Whatever it does else
}
public sealed class MyAPI : IMyApi, IMyApiBuilder
{
public static IMyApiBuilder Builder = new MyAPI();
private MyAPI()
{
// CTOR ...
}
// vv Notice _explicit_ interface implemenations.
// https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation
IMyApi IMyApiBuilder.Build() { return this; }
void IMyApi.PressTheRedButton()
{
// ...
}
}
// USAGE:
IMyApi api = MyAPI.Builder.Build();
Thank you so much Fildor and ema! The ideas of adding a factory method, a factor interface or even a full-blown builder is definitely good solutions! And it got me thinking about how to incorporate them into my DLL while still sparing its users. They don't need to know that it in fact is a foul smelling factory with polluting smokestack emissions that are creating the instance :)
Then I came across Default Interface Methods and the structure of my approach ended up being
public interface MyQuestionableDll
{
static readonly MyQuestionableDll Instance = new QuestionableImplementation();
void PressTheRedButtonBelowTheDoNotPushSign();
}
internal class QuestionableImplementation : MyQuestionableDll
{
public void PressTheRedButtonBelowTheDoNotPushSign()
{
// Distribute German Volksmusik at local school
}
}
// and the use case
var questionableInstance = MyQuestionableDll.Instance;
questionableInstance.PressTheRedButtonBelowTheDoNotPushSign();
Thanks again Fildor and ema!
- Jakob
I wonder since there is no way how to implement a generic Decorator class in C# (is it?) like this:
public class Decorator<TDecoratorIterface> : TDecoratorInterface
{
public TDecoratorInterface Component {get; private set;}
protected Decorator(TDecoratorInterface component)
{
Component = component;
}
}
use like this:
public interface IDogDecorator
{
void Bark();
}
public class Dog : IDogDecorator
{
public void Bark()
{
Console.Write("I am a dog");
}
}
public class StinkingDog : Decorator<IDogDecorator>
{
public StinkingDog(IDogDecorator dog):base(dog)
{
}
public void Bark()
{
Component.Bark();
Console.WriteLine(" and I stink");
}
}
can such a thing be managed via PostSharp or any other AOP framework for .NET?
thank fro your answers, I spent half a day trying to create such a construct without any success, so any help is appreciatted:)
There's no direct equivalent to this construct, as C# doesn't allow the base class of a type to be dynamic. Remember that the generic type must be fully defined at compile time, not at usage time.
There's multiple possible ways to go: In the example above, the StinkingDog should just implement the IDogDecorator interface. So just specify that there. You're forwarding calls anyway.
public class StinkingDog : Decorator<IDogDecorator>, IDogDecorator
There would probably be frameworks that do what you want exactly (i.e. Rhino.Mocks is actually creating Mocks this way), but for production code, I'd really suggest not doing any AOP approach. It's clumsy and slow.
I am making a payment system for my site. Users can select one of several payment providers to pay, but all should behave in the same way. I thought to represent this behavior like this:
public abstract class PaymentProvider {
private static var methods = Dictionary<String,PaymentProvider>
{
{"paypal",new PaymentProviderPaypal()},
{"worldpay",new PaymentProviderWorldpay()}
}
public static Dictionary<String,PaymentProvider> AllPaymentProviders
{
get {return methods;}
}
public abstract pay();
}
public class PaymentProviderPaypal : PaymentProvider {
public override pay() {
}
}
public class PaymentProviderWorldpay : PaymentProvider {
public override pay() {
}
}
You are supposed to use this by writing PaymentProvider.AllPaymentProviders["key"].pay(). The idea is that the functions using this class don't need to know about how the underlying payment provider is implemented, they just need to know the key.
However, at the moment, if you have access to the PaymentProvider class, you also have access to the inheriting classes. Its possible to instantiate a new copy of the inheriting classes, and make use of them in an unexpected way. I want to encapsulate the inheriting classes so that only the abstract PaymentProvider knows about them.
How should I do this? Different protection levels like protected don't work here - In Java, protected means that only other classes in the namespace can use that class, but in C# it means something else.
Do I have the right idea here? Or should I use a different method?
A couple of options spring to mind:
Put this in a separate assembly from the client code, and make the implementations abstract
Put the implementations inside the PaymentProvider class as private nested classes. You can still separate the source code by making PaymentProvider a partial class - use one source file per implementation
The first option is likely to be the cleanest if you don't mind separating the clients from the implementation in terms of assemblies.
Note that both of these are still valid options after the change proposed by Jamiec's answer - the "visibility" part is somewhat orthogonal to the inheritance part.
(As an aside, I hope the method is really called Pay() rather than pay() :)
Your inheritance heirachy is a bit wonky, I would be tempted to do it a similar but crucially different way.
public interface IPaymentProvider
{
void Pay()
}
// Implementations of IPaymentProvider for PaypalPaymentProvider & WorldpayPaymentProvider
public static class PaymentHelper
{
private static var providers = Dictionary<String,IPaymentProvider>
{
{"paypal",new PaymentProviderPaypal()},
{"worldpay",new PaymentProviderWorldpay()}
}
public static void Pay(string provider)
{
if(!providers.Containskey(provider))
throw new InvalidOperationException("Invalid provider: " + provider);
providers[provider].Pay();
}
}
Then the usage would be something like PaymentHelper.Pay("paypal").
Obviously if there is more data to provide to the Pay method this can be added to both the interface, and the helper. for example:
public interface IPaymentProvider
{
void Pay(double amount);
}
public static void Pay(string provider, double amount)
{
if(!providers.Containskey(provider))
throw new InvalidOperationException("Invalid provider: " + provider);
providers[provider].Pay(amount);
}
I m trying to understand Interfaces so that I can implement them in my programs but I m not able to imagine how should i use them.
Also give me some eg of using them with multiple inheritance in C#
A good example for an interface is a repository pattern. Your interface will define methods like Get, GetAll, Update, Delete, etc. No implementation, just function signatures.
Then, you can write a 'concrete' implementation of that class to work with, say, MySQL. Your UI should only refer to the interface, though.
Later, if you decide to change to Microsoft SQL, you write another concrete implementation, but your UI code doesn't have to change (much).
Multiple inheritance doesn't exist in C#, in the sense that you can only inherit from one 'concrete' class; though you can inherit (or 'implement') as many interfaces as you want.
I am writing a video game. In this video game I apply different forces to objects in the game. Thrust forces, impact forces, gravitational forces. While they are calculated differently, they all have the same basic elements. I need to call an update function that will evaluate the force and add the force to the object it's attached to.
So, what I've done is create an IForce interface that has an update function for its signature. All of my forces implement this interface:
public interface IForce
{
void Update(Particle particle, GameTime gameTime);
}
Here is a sample implementation.
public class Spring : IForce
{
private Particle ThisParticle;
private Particle ThatParticle;
private float K;
public Spring(Particle thisParticle, Particle thatParticle, float k)
{
ThisParticle = thisParticle;
ThatParticle = thatParticle;
}
public void Update(Particle particle, GameTime gameTime)
{
float X = Vector3.Length(ThisParticle - ThatParticle);
ThisParticle.Forces.Add(K * X);
}
}
The update function has a simplified spring force update to make it easier to understand.
This helps in a few ways.
I can completely change the way a force is calculated without effecting other parts of my code. I do this all the time. Along the same lines, it is rediculously easy for me to add new forces. As long as it implements the IForce interface I know it will mesh well with my existing code.
Another way it helps is with handling a large number of forces. I have a force registry that has a List of IForce. Since all forces implement that interface and have an Update function it's very easy to update all the forces in my game. When I create the force I add it to the list. Then, I loop through the list and call each elements update function without worrying about what type of force it is and all my forces update.
I use interfaces every day in a lot of different situations. They are fantastic!
Note :Interface is used to restrict and access the methods or events etc from differents classes at any cost, It means we can defined many more methods inside any class but when we are calling methods through Interface means we want only other than restricted methods. In the program below User1 can use Read & Write both but User2 can Write and Execute. See this Program below.........
namespace ExplConsole
{
class Program
{
static void Main ()
{
System.Console.WriteLine("Permission for User1");
User1 usr1 = new Test(); // Create instance.
usr1.Read(); // Call method on interface.
usr1.Write();
System.Console.WriteLine("Permission for User2");
User2 usr2 = new Test();
usr2.Write();
usr2.Execute();
System.Console.ReadKey();
}
}
interface User1
{
void Read();
void Write();
}
interface User2
{
void Write();
void Execute();
}
class Test : NewTest,User1, User2
{
public void Read()
{
Console.WriteLine("Read");
}
public void Write()
{
Console.WriteLine("Write");
}
}
class NewTest
{
public void Execute()
{
Console.WriteLine("Execute");
}
}
}
Output:
Permission for User1
Read
Write
Permission for User2
Write
Execute
Interfaces simply define a contract of the public elements (e.g. properties, methods, events) for your object, not behavior.
interface IDog
{
void WagTail(); //notice no implementation
ISound Speak(); //notice no implementation
}
class Spaniel : IDog
{
public void WagTail()
{
Console.WriteLine("Shook my long, hairy tail");
}
public ISound Speak()
{
return new BarkSound("yip");
}
}
class Terrier : IDog
{
public void WagTail()
{
Console.WriteLine("Shook my short tail");
}
public ISound Speak()
{
return new BarkSound("woof");
}
}
UPDATE
In "real examples" I use interfaces with:
- Unit Testing
- GENERICS (e.g. Repository, Gateway, Settings)
interface Repository<T>{
T Find(Predicate<T>);
List<T> ListAll();
}
interface Gateway<T>{
T GetFrom(IQuery query);
void AddToDatabase(IEntity entityItem);
}
interface Settings<T>{
string Name { get; set; }
T Value { get; set; }
T Default { get; }
}
Here is one (in Java, but this is not important since they're similiar):
In my project I've created simple interface:
public interface Identifiable<T> {
public T getId();
}
Which is simple replacement to some sorts of annotations. The next step: I've made all entity classes implement this interface.
The third step is to write some syntax-sugar-like methods:
public <T> List<T> ids(List<? extends Identifiable<T> entities) { ... }
This was just an example.
The more complex example is something like validation rules: you have some validation engine (probably written by you) and a simple interface for rule:
public interface ValidationRule {
public boolean isValid(...);
}
So, this engine requires the rules to be implemented by you. And of course there will be multiple inheritance since you'll certainly wish more then a single rule.
Multiple inheritance is about having a class be usable in multiple situations: [pseudo code]
interface Shape {
// shape methods like draw, move, getboundingrect, whatever.
}
interface Serializable {
// methods like read and write
}
class Circle : public Shape, public Serializable {
// TODO: implement Shape methods
// TODO: implement Serializable methods
}
// somewhere later
{
Circle circle;
// ...
deserializer.deserialize(circle);
// ...
graphicsurface.draw(circle);
// ...
serializer.serialize(circle);
}
The idea is that your Circle class implements two different interfaces that are used in very different situations.
Sometimes being too abstract just gets in the way and referring to implementation details actually clarifies things. Therefore, I'll provide the close to the metal explanation of interfaces that made me finally grok them.
An interface is just a way of declaring that a class implements some virtual functions and how these virtual functions should be laid out in the class's vtable. When you declare an interface, you're essentially giving a high-level description of a virtual function table to the compiler. When you implement an interface, you're telling the compiler that you want to include the vtable referred to by that interface in your class.
The purpose of interfaces is that you can implicitly cast a class that implements interface I to an instance of interface I:
interface I {
void doStuff();
}
class Foo : I {
void doStuff() {}
void useAnI(I i) {}
}
var foo = new Foo();
I i = foo; // i is now a reference to the vtable pointer for I in foo.
foo.useAnI(i); // Works. You've passed useAnI a Foo, which can be used as an I.
The simple answer, in my opinion, and being somewhat new to interfaces myself is that implementing an interface in a class essentially means: "This class MUST define the functions (and parameters) in the interface".
From that, follows that whenever a certain class implements the interface, you can be sure you are able to call those functions.
If multiple classes which are otherwise different implement the same interface, you can 'cast' them all to the interface and call all the interface functions on them, which might have different effects, since each class could have a different implementation of the functions.
For example, I've been creating a program which allows a user to generate 4 different kinds of maps. For that, I've created 4 different kind of generator classes. They all implement the 'IGenerator' interface though:
public interface IGenerator {
public void generateNow(int period);
}
Which tells them to define at least a "public generateNow(int period)" function.
Whatever generator I originally had, after I cast it to a "IGenerator" I can call "generateNow(4)" on it. I won't have to be sure what type of generator I returned, which essentially means, no more "variable instanceof Class1", "variable instanceof Class2" etc. in a gigantic if statement anymore.
Take a look at something you are familiar with - ie a List collection in C#. Lists define the IList interface, and generic lists define the IList interface. IList exposes functions such as Add, Remove, and the List implements these functions. There are also BindingLists which implement IList in a slightly different way.
I would also recommend Head First Design Patterns. The code examples are in Java but are easily translated into C#, plus they will introduce you to the real power of interfaces and design patterns.
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).