How to extend .net interface without modifying it? - c#

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
}
}

Related

Understanding Interfaces 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.

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

Partially implement an Interface

I asked something similar but still I haven't got a clear idea. My objective is to partially implement an interface in C#.
Is it possible? Is there any pattern to achieve this result?
An interface defines a contract. You have to fulfill that contract by implementing all of its members if you want to use it.
Maybe the use of an abstract class would work best for you, that way you can define some default behavior while allowing overrides where you need to.
You can throw NotImplementedException for the methods you don't want to implement or NotSupportedException for the methods you can't implement.
It's preferable to not do this, but there are places in the .NET framework where classes throw NotSupportedExceptions and the design of Stream pretty much forces you to throw this exception for some methods.
From MSDN about NotSupportedException:
The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
yes you can partially implement interface if you are using abstract class something like this:
public interface myinterface
{
void a();
void b();
}
public abstract class myclass : myinterface
{
public void a()
{
///do something
}
public abstract void b(); // keep this abstract and then implement it in child class
}
As others have said an interface should be fully implemented (although there are ways around this like throwing NotSupportedExceptions)
You should take a look at The Interface Segregation Principle (one of the SOLID priciples that Robert Martin discusses) and figure out if you actually need multiple interfaces that classes can then choose which ones to implement
Like the other posts, throwing an exception in addition to hiding the member is your best bet.
interface IPartial
{
void A();
void B();
}
class Partial : IPartial
{
public void A()
{
// Implementation here
}
void IPartial.B()
{
throw new NotImplementedException();
}
}
class Main
{
Main()
{
Partial t = new Partial();
t.A();
t.B(); // Compiler error
IPartial s = new Partial();
s.A();
s.B(); // Runtime error
}
}
It is entirely possible that implementation of SOME of the methods in the Interface are common to a group of classes, while the rest need to be uniquely implemented.
Using abstract classes kind of require you to re-declare the unimplemented methods using the abstract methods, which is redundant as you have the declaration already in the interface. Exceptions approach is not the best either because if you are not careful, you will get to know what you have "missed" implementing only at runtime when you see the error message.
Here is a way to do this without abstract classes and without using Exceptions. One of the methods in the interface is implemented in a separate (perhaps common) way. Thus you are only required to implement the "rest" in your Implementation class.
interface Interface
{
void A();
void B();
}
class PartialImplementer
{
public void B()
{
// common implementation
}
}
class Implementation : PartialImplementer, Interface
{
public void A()
{
// unique implementation
}
}
I had a bunch of Query classes with a common interface, but I was not implementing all the methods. The methods I did not implement throw NotImplementedException. But I did not like it.
So I broke my interface into 4 interfaces like this:
Before
public interface ICrudQueries<TIndexViewModel, TDetailsViewModel, TCreateViewModel, TEditViewModel>
{
Task<TIndexViewModel> GetIndexViewModel(TIndexViewModel viewModel = default);
Task<TDetailsViewModel> GetDetailsViewModel(int id);
Task<TCreateViewModel> GetCreateViewModel();
Task<TCreateViewModel> SetSelectLists(TCreateViewModel viewModel);
Task<TEditViewModel> SetSelectLists(TEditViewModel viewModel);
Task<TEditViewModel> GetEditViewModel(int id);
}
After
public interface IDetailsQuery<TDetailsViewModel>
{
Task<TDetailsViewModel> GetDetailsViewModel(int id);
}
public interface ICreateQuery<TCreateViewModel>
{
Task<TCreateViewModel> GetCreateViewModel();
Task<TCreateViewModel> SetSelectLists(TCreateViewModel viewModel);
}
public interface IEditQuery<TEditViewModel>
{
Task<TEditViewModel> SetSelectLists(TEditViewModel viewModel);
Task<TEditViewModel> GetEditViewModel(int id);
}
public interface IIndexQuery<TIndexViewModel>
{
Task<TIndexViewModel> GetIndexViewModel(TIndexViewModel viewModel = default);
}
Now I can implement them separately and I don't have to throw NotImplementedException. I can implement one or more on the same class.
You can even use the original interface as-is like this!
/// <summary>
/// Enforce good practice and naming standards for ViewModel Query classes.
/// Allow allow partial implementation by using any of the other interface(s).
/// </summary>
public interface ICrudQueries<TIndexViewModel, TDetailsViewModel, TCreateViewModel, TEditViewModel> :
IIndexQuery<TIndexViewModel>,
IDetailsQuery<TDetailsViewModel>,
ICreateQuery<TCreateViewModel>,
IEditQuery<TEditViewModel>
{
}

Categories