Understanding Interfaces C# - c#

Been reading all day on interfaces and abstract classes trying to get a grasp on them to better understand the amazon library I'm working with. I have this code:
using MWSClientCsRuntime;
namespace MarketplaceWebServiceOrders.Model
{
public interface IMWSResponse : IMwsObject
{
ResponseHeaderMetadata ResponseHeaderMetadata { get; set; }
}
and
namespace MWSClientCsRuntime
{
public interface IMwsObject
{
void ReadFragmentFrom(IMwsReader r);
string ToXML();
string ToXMLFragment();
void WriteFragmentTo(IMwsWriter w);
void WriteTo(IMwsWriter w);
}
}
My first questions is I thought Interfaces cannot contain fields, however they can contain properties usch as ResponseHeaderMetadata?
Second, in my main program I have this line of code:
IMWSResponse response = null;
with response being later used to store the information that amazon sends back after a method call is invoked. But what is the meaning behind setting a variable of an interface type to null?
Also, a interface can implement another interface? It isn't only classes that can implement interfaces, but interfaces themselves as well?

Pproperties can be present in interfaces since properties are actually methods - the use of T GetSomeValue() alongside void SetSomeValue(T value) became so common in other languages, that C# implements these as properties.
The meaning behind setting an interface member to null is the same as setting anyother property to null - since a property's set accessor is a method, it's like calling any other method on the interface. What null means where is up to the implementation.
Interfaces do not implement each other, since and interface cannot contain code and therefore is not implementing; Interface inheritance allows one to require one interface in another. A big example is IEnumerable<T>, which is so closely tied to IEnumerable that it inherits, thus meaning any class implementing IEnumerable<T> must also implement IEnumerable.

An interface is like a contractual agreement. By inheriting an interface from a class, you are saying, "I agree to implement all of the methods defined in this interface". So if you have an interface like this:
public interface IWorker {
void DoWork();
}
and you use that interface like this:
public class Employee : IWorker
{
// you are forced to implement this method
void DoWork {}
}
public class Contractor: IWorker
{
// you are forced to implement this method
void DoWork {}
}
By "inheriting" interfaces by other interfaces, you are simply agreeing to implement any methods in the other interfaces, like so (from MSDN):
interface IBase
{
void F();
}
interface IDerived: IBase
{
void G();
}
class C: IDerived
{
void IBase.F() {...}
void IDerived.G() {...}
}
class D: C, IDerived
{
public void F() {...}
public void G() {...}
}
You do not have to set a variable of an interface type to null, though you have the power to do so. The great thing about interfaces is that you are able to set a variable of the type of interface, to anything that "inherits" that interface.

Related

What is the reason behind C# allowing the overloading of interface properties? [duplicate]

So, what exactly is a good use case for implementing an interface explicitly?
Is it only so that people using the class don't have to look at all those methods/properties in intellisense?
If you implement two interfaces, both with the same method and different implementations, then you have to implement explicitly.
public interface IDoItFast
{
void Go();
}
public interface IDoItSlow
{
void Go();
}
public class JustDoIt : IDoItFast, IDoItSlow
{
void IDoItFast.Go()
{
}
void IDoItSlow.Go()
{
}
}
It's useful to hide the non-preferred member. For instance, if you implement both IComparable<T> and IComparable it is usually nicer to hide the IComparable overload to not give people the impression that you can compare objects of different types. Similarly, some interfaces are not CLS-compliant, like IConvertible, so if you don't explicitly implement the interface, end users of languages that require CLS compliance cannot use your object. (Which would be very disastrous if the BCL implementers did not hide the IConvertible members of the primitives :))
Another interesting note is that normally using such a construct means that struct that explicitly implement an interface can only invoke them by boxing to the interface type. You can get around this by using generic constraints::
void SomeMethod<T>(T obj) where T:IConvertible
Will not box an int when you pass one to it.
Some additional reasons to implement an interface explicitly:
backwards compatibility: In case the ICloneable interface changes, implementing method class members don't have to change their method signatures.
cleaner code: there will be a compiler error if the Clone method is removed from ICloneable, however if you implement the method implicitly you can end up with unused 'orphaned' public methods
strong typing:
To illustrate supercat's story with an example, this would be my preferred sample code, implementing ICloneable explicitly allows Clone() to be strongly typed when you call it directly as a MyObject instance member:
public class MyObject : ICloneable
{
public MyObject Clone()
{
// my cloning logic;
}
object ICloneable.Clone()
{
return this.Clone();
}
}
Another useful technique is to have a function's public implementation of a method return a value which is more specific than specified in an interface.
For example, an object can implement ICloneable, but still have its publicly-visible Clone method return its own type.
Likewise, an IAutomobileFactory might have a Manufacture method which returns an Automobile, but a FordExplorerFactory, which implements IAutomobileFactory, might have its Manufacture method return a FordExplorer (which derives from Automobile). Code which knows that it has a FordExplorerFactory could use FordExplorer-specific properties on an object returned by a FordExplorerFactory without having to typecast, while code which merely knew that it had some type of IAutomobileFactory would simply deal with its return as an Automobile.
It's also useful when you have two interfaces with the same member name and signature, but want to change the behavior of it depending how it's used. (I don't recommend writing code like this):
interface Cat
{
string Name {get;}
}
interface Dog
{
string Name{get;}
}
public class Animal : Cat, Dog
{
string Cat.Name
{
get
{
return "Cat";
}
}
string Dog.Name
{
get
{
return "Dog";
}
}
}
static void Main(string[] args)
{
Animal animal = new Animal();
Cat cat = animal; //Note the use of the same instance of Animal. All we are doing is picking which interface implementation we want to use.
Dog dog = animal;
Console.WriteLine(cat.Name); //Prints Cat
Console.WriteLine(dog.Name); //Prints Dog
}
It can keep the public interface cleaner to explicitly implement an interface, i.e. your File class might implement IDisposable explicitly and provide a public method Close() which might make more sense to a consumer than Dispose().
F# only offers explicit interface implementation so you always have to cast to the particular interface to access its functionality, which makes for a very explicit (no pun intended) use of the interface.
If you have an internal interface and you don't want to implement the members on your class publicly, you would implement them explicitly. Implicit implementations are required to be public.
Another reason for explicit implementation is for maintainability.
When a class gets "busy"--yes it happens, we don't all have the luxury of refactoring other team members' code--then having an explicit implementation makes it clear that a method is in there to satisfy an interface contract.
So it improves the code's "readability".
A different example is given by System.Collections.Immutable, in which the authors opted to use the technique to preserve a familiar API for collection types while scraping away the parts of the interface that carry no meaning for their new types.
Concretely, ImmutableList<T> implements IList<T> and thus ICollection<T> (in order to allow ImmutableList<T> to be used more easily with legacy code), yet void ICollection<T>.Add(T item) makes no sense for an ImmutableList<T>: since adding an element to an immutable list must not change the existing list, ImmutableList<T> also derives from IImmutableList<T> whose IImmutableList<T> Add(T item) can be used for immutable lists.
Thus in the case of Add, the implementations in ImmutableList<T> end up looking as follows:
public ImmutableList<T> Add(T item)
{
// Create a new list with the added item
}
IImmutableList<T> IImmutableList<T>.Add(T value) => this.Add(value);
void ICollection<T>.Add(T item) => throw new NotSupportedException();
int IList.Add(object value) => throw new NotSupportedException();
In case of explicitly defined interfaces, all methods are automatically private, you can't give access modifier public to them. Suppose:
interface Iphone{
void Money();
}
interface Ipen{
void Price();
}
class Demo : Iphone, Ipen{
void Iphone.Money(){ //it is private you can't give public
Console.WriteLine("You have no money");
}
void Ipen.Price(){ //it is private you can't give public
Console.WriteLine("You have to paid 3$");
}
}
// So you have to cast to call the method
class Program
{
static void Main(string[] args)
{
Demo d = new Demo();
Iphone i1 = (Iphone)d;
i1.Money();
((Ipen)i1).Price();
Console.ReadKey();
}
}
// You can't call methods by direct class object
This is how we can create Explicit Interface:
If we have 2 interface and both the interface have the same method and a single class inherit these 2 interfaces so when we call one interface method the compiler got confused which method to be called, so we can manage this problem using Explicit Interface.
Here is one example i have given below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops3
{
interface I5
{
void getdata();
}
interface I6
{
void getdata();
}
class MyClass:I5,I6
{
void I5.getdata()
{
Console.WriteLine("I5 getdata called");
}
void I6.getdata()
{
Console.WriteLine("I6 getdata called");
}
static void Main(string[] args)
{
MyClass obj = new MyClass();
((I5)obj).getdata();
Console.ReadLine();
}
}
}

How to extend .net interface without modifying it?

I'll start by saying that I am not a professional developer but have a ton of code that is used by various companies, mainly written with .net c# and vb.
With that said, I've never felt the need to get into extending existing classes and interfaces, and I'm struggling a bit now that I do want to do this, here's an example:
I have added a COM reference to my project of another application (can't edit this).
This reference has an interface that I want to extend, for example, _CellObject, I want to add some methods to it. In the past I'd build my own class to handle this, which works, but I think the more appropriate way would be to extend it.
So I build another interface, inherit from _CellObject and add my new methods.
Then I build a class that implements that interface, and this is where I realize I'm doing something wrong, all the methods from original interface must be added, but I don't want to do that. It's like I'm missing a "partial" somewhere or maybe this isn't possible?
Can someone push me in the right direction here?
It's true. If you extend an interface by inheriting from it, then when you implement a class that inherits from your new interface you will need to implement all the methods from your interface and the one it inherits from. In a sense, that's kinda the point of having a new interface inherit from an existing one. Otherwise you could just make a new interface and not inherit from an existing one.
COM objects don't support implementation inheritance or polymorphism, so there won't be any protected members for you to override. I don't typically see developers try to extend COM objects. If you need to add related functionality, you can wrap it (composition over inheritance) or you can write extension methods.
Your fourth point makes me assume you have some default-implementation of the existing interface that you want to re-use within the new one. As others already mentioned you can extend the existing interface by inheriting. However you also need to implement the "old" methods within a class implementing the new interface.
If you want to re-use the default-implementaion within your new class, you can just provide it to its constructor. So you have this code:
interface IBase
{
void DoSomething();
}
interface IDerived : IBase
{
void SoSomethingMore();
}
class MyBase : IBase
{
public void DoSomething() { ... }
}
class MyDerived : IDerived
{
private readonly MyBase _m;
public MyDerived(MyBase m) { this._m = m; }
// now you only need to forward the call for the existing interface to the injected base-class
public void DoSomething() => this._m.DoSomething();
public void DoSomethingMore() => ...
}
One option (excluding the issues you have with COM) is to create a new interface and class which include the functionality of the older versions. Now your new class can inherit from the original class, keeping it's functionality while extending it with a new interface.
public interface _CellObject
{
void DoSomething();
}
public interface _CellObject2 : _CellObject
{
void DoSomethingElse();
}
public class CellObject : _CellObject
{
public void DoSomething()
{
}
}
public class CellObject2 : CellObject, _CellObject2
{
public void DoSomethingElse()
{
DoSomething();
}
}
Simply you extend another Interface from your existing Interface, this is called Interface Segregation.
public interface IContract
{
void DoSomething();
}
public interface IContractChanged:IContract
{
void DoSomethingMore();
}
And now you can implement the new contract IContractChanged to meet your needs.
There are actaully two way to extend interface without modifying it. First create antoher interface that inherit from that interface. Imagine you have Interface A and you want to extend it.
interface A
{
void SomeMethodA();
}
interface B :A
{
void SomeMethodB();
}
Second you can directly implement that interface.
class C : A
{
public void SomeMethodA()
{
//your actual implementation
}
}

Workaround for being unable to put code in interfaces

Let's say I have an interface that many many distinct classes implement:
public interface IHaveObjects
{
object firstObject();
}
(Note: I can't make it an abstract base class as implementors of IHaveObjects may already have a base class.)
Now I want to add a new method to the interface, so that one implementer of the interface can have special behaviour for it. Ideally I would do something like this:
public interface IHaveObjects
{
object firstObject();
object firstObjectOrFallback()
{
return firstObject();
}
}
then go to that one implementor of the interface and give it the override:
public class ObjectHaverPlus : IHaveObjects
{
public override object IHaveObjects.firstObjectOrFallback()
{
return firstObject() ?? getDefault();
}
}
However it is forbidden in C# to provide a method body in an interface, and I would like to avoid going to every single implementer of IHaveObjects to drop in a definition of firstObjectOrFallback(). (Imagine if there are hundreds or thousands)
Is there a way to do this without lots of copy paste?
How about introducing a second interface which inherits from IHaveObjects.
Than you only have to change these classes, which need the new interface with the new method.
This looks like:
interface I1
{
void Method1();
}
interface I2 : I1
{
void Method2();
}
That's the problem with interfaces - they don't have any default implementation so any changes to them are breaking changes - i.e. code needs to be modified to work with new version of interface.
Since your implementations already have base classes on their own - you cannot turn it into abstract class, nor does C# have multiple class inheritance.
What you can do is to think - is it really a method on interface? Or could it be implemented as an extension method on interface (didn't try that but I suppose it will work just fine)?
If it is a method on interface and it should stay there - you may think of breaking this interface into two parts, second inheriting from the first (IHaveObjectsAndSupportDefault : IHaveObjects) and use this interface where default value is truly needed (like some other answers indicate).
I may have misunderstood your question, but why not use a second interface, something like:
public interface IHaveObjectsEnhanced
{
object FirstObjectOrFallback();
}
Then you could implement the first and second interface:
public class ObjectHaverPlus : IHaveObjects, IHaveObjectsEnhanced
{
public object FirstObject()
{
}
public object FirstObjectOrFallback()
{
return FirstObject() ?? GetDefault();
}
}

Ignoring Interface method implementation in C#

Suppose an Interface I has two methods. For example Method1() and Method2().
A class A Implements an Interface I.
Is it possible for class A to implement only Method1() and ignore Method2()?
I know as per rule class A has to write implementation of both methods. I am asking if there any way to violate this rule?
You can avoid implementing it (a valid scenario) but not ignore it altogether (a questionable scenario).
public interface IFoo
{
void A();
void B();
}
// This abstract class doesn't know what to do with B(), so it puts
// the onus on subclasses to perform the implementation.
public abstract class Bar : IFoo
{
public void A() { }
public abstract void B();
}
No, there's no such concept in C# of optional interface members. If A implements I, then it must provide some implementation for all of I's members, even if the implementation does nothing or only throws an exception.
public class A : I
{
public void Method1()
{
// Do nothing.
}
public void Method2()
{
throw new NotImplementedException();
}
}
From a design perspective, why would you want to do this anyway in a statically typed language? Furthermore, why not just have two interfaces?
public interface I1 { void Method1(); }
public interface I2 { void Method2(); }
With your interfaces coded like this, you can have classes that implement one interface or the other, or both, or neither. To me, this makes more sense anyway.
UPDATE 2018-06-13
The C# lang Git Hub has a proposal in progress for default interface methods. In short, the interface developer would be able to provide an implementation for a method or methods in the interface itself, and the developer using the interface on their class or struct would not have to implement those methods explicitly. Not exactly what the OP was asking about, but potentially useful.
You must implement all methods of the interfaces your class inherits from. There is no way around that. But you can use explicit interface implementation to hide the method.
That way a user doesn't see the method on a variable that has the class as type, but when he casts to the interface he can call the method.
class A : I
{
void I.Method2()
{
throw new NotSupportedException();
}
}
then
A a;
a.Method2(); //doesn't compile
I i = a;
i.Method2(); //works
If the class A is only an abstract base class, you can also use an abstract method to implement the interface, leaving the concrete implementation to the derived classes.
No, there's not.
But you can code :
public void Method2(){
throw new NotImplementedException();
}
That will inform the application that this method cannot be called from this instance.
Yes if I was a class, but No if it's an interface.

Interface wonder question

We define interface as below:
interface IMyInterface
{
void MethodToImplement();
}
And impliments as below:
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
instead of creating a interface , why can we use the function directly like below :-)
class InterfaceImplementer
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Any thoughts?
You are not implementing the interface in the bottom example, you are simply creating an object of InterfaceImplementer
EDIT: In this example an interface is not needed. However, they are extremely useful when trying to write loosely coupled code where you don't have to depend on concrete objects. They are also used to define contracts where anything implementing them has to also implement each method that it defines.
There is lots of information out there, here is just a brief intro http://www.csharp-station.com/Tutorials/Lesson13.aspx
If you really want to understand more about interfaces and how they can help to write good code, I would recommend the Head First Design Patterns book. Amazon Link
instead of creating a interface , why
can we use the function directly like
below
Are you asking what the point of the interface is?
Creating an interface allows you to decouple your program from a specific class, and instead code against an abstraction.
When your class is coded against an interface, classes that use your class can inject whichever class they want that implements this interface. This facilitates unit testing since not-easily-testable modules can be substituted with mocks and stubs.
The purpose of the interface is for some other class to be able to use the type without knowing the specific implementation, so long as that type conforms to a set of methods and properties defined in the interface contract.
public class SomeOtherClass
{
public void DoSomething(IMyInterface something)
{
something.MethodToImplement();
}
}
public class Program
{
public static void Main(string[] args)
{
if(args != null)
new SomeOtherClass().DoSomething(new ImplementationOne());
else
new SomeOtherClass().DoSomething(new ImplementationTwo());
}
}
Your example doesn't really follow that pattern, however; if one that one class implements the interface, then there really isn't much of a point. You can call it either way; it just depends on what kind of object hierarchy you have and what you intend to do for us to say whether using an interface is a good choice or not.
To sum: Both snippets you provide are valid code options. We'd need context to determine which is a 'better' solution.
Interfaces are not required, there is nothing wrong with the last section of code you posted. It is simply a class and you call one of it's public methods. It has no knowledge that an interface exists that this class happens to satisfy.
However, there are advantages:
Multiple Inheritance - A class can only extend one parent class, but can implement any number of interfaces.
Freedom of class use - If your code is written so that it only cares that it has an instance of SomethingI, you are not tied to a specific Something class. If tomorrow you decide that your method should return a class that works differently, it can return SomethingA and any calling code will not need to be changed.
The purpose of interfaces isn't found in instantiating objects, but in referencing them. Consider if your example is changed to this:
static void Main()
{
IMyInterface iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
Now the iTmp object is of the type IMyInterface. Its specific implementation is InterfaceImplementer, but there may be times where the implementation is unimportant (or unwanted). Consider something like this:
interface IVehicle
{
void MoveForward();
}
class Car : IVehicle
{
public void MoveForward()
{
ApplyGasPedal();
}
private void ApplyGasPedal()
{
// some stuff
}
}
class Bike : IVehicle
{
public void MoveForward()
{
CrankPedals();
}
private void CrankPedals()
{
// some stuff
}
}
Now say you have a method like this somewhere:
void DoSomething(IVehicle)
{
IVehicle.MoveForward();
}
The purpose of the interface becomes more clear here. You can pass any implementation of IVehicle to that method. The implementation doesn't matter, only that it can be referenced by the interface. Otherwise, you'd need a DoSomething() method for each possible implementation, which can get messy fast.
Interfaces make it possible for an object to work with a variety of objects that have no common base type but have certain common abilities. If a number of classes implement IDoSomething, a method can accept a parameter of type IDoSomething, and an object of any of those classes can be passed to it. The method can then use all of the methods and properties applicable to an IDoSomething without having to worry about the actual underlying type of the object.
The point of the interface is to define a contract that your implementing class abides by.
This allows you to program to a specification rather than an implementation.
Imagine we have the following:
public class Dog
{
public string Speak()
{
return "woof!";
}
}
And want to see what he says:
public string MakeSomeNoise(Dog dog)
{
return dog.Speak();
}
We really don't benefit from the Interface, however if we also wanted to be able to see what kind of noise a Cat makes, we would need another MakeSomeNoise() overload that could accept a Cat, however with an interface we can have the following:
public interface IAnimal
{
public string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "woof!";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "meow!";
}
}
And run them both through:
public string MakeSomeNoise(IAnimal animal)
{
return animal.Speak();
}

Categories