Ignoring Interface method implementation in C# - 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.

Related

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

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.

C# interface method declared in Base class need not be again implemented in Derived class

It could be a silly question, but I am learning, and I was just curious what's happening, today I was playing with few oops concepts and learning it in VS. I was again puzzled to see that we don't have to implement multiple interfaces same method into a derived class where ACTUALLY we "inherit" the interface, but in base class.
May I know how it works? My concern is, even though I do not "inherit" interface methods in base class, I use a method with same name. I also do not implement it in derived class.
Can somebody help me understand what's happening and how and why?
Class A
{
public void Display()
{
Console.Writeline("I am from A");
}
}
interface IA
{
void Display();
}
interface IB
{
void Display();
}
Class B : A, IA, IB
{
}
Class Final
{
static void Main()
{
B b = new B();
b.Display(); // displays class A Display method.
Console.Readline();
}
}
Although I can't speak for the language team, you can answer this question by posing the alternative solution.
You want to know why B is considered to implement the interface IA even though the required method definition is in base class A, which doesn't implement the interface. So, let's consider the opposite: B should not be considered to implement the interface because the base class' method wasn't written with that interface in mind.
This means that your code doesn't compile. Why doesn't it compile? Because B doesn't implement required member Display of interface IA.
To fix this, you'd add a method Display to class B. That fixes the interface implementation. However, you now have a new compilation problem: you'll see a warning "B.Display()' hides inherited member 'ConsoleApplication1.A.Display()'. Use the new keyword if hiding was intended."
This is because your A.Display wasn't overrideable - and you don't want to override it. You can implement a method to call base.Display() if you choose, but this is extra code to essentially do nothing, and it makes a mess of your inheritance since a new method is handled differently to an override. (If you write A x = new B(); x.Display(); then you'll actually call A.Display() directly, which could get messy as your code evolves and is an accident waiting to happen.)
Alternatively, you might implement an entirely new B.Display method. What you've also now done is hidden the method implemented in class A from anyone who might derive from B or create an instance of B. Using new to hide methods is rarely a recipe for an understandable object structure, and this would be no exception - all so that you can implement an interface cleanly.
So ultimately, I would imagine, this decision was made because the alternative is far too messy.
The reason is because the implementation is "implied" -- an implicit implementation of an interface.
Class A
{
public void Display()
{
Console.Writeline("I am from A");
}
}
interface IA
{
void Display();
}
interface IB
{
void Display();
}
Class B : A, IA, IB
{
void AI.Display() { Console.Writeline("I am from AI.Display"); }
}
Class Final
{
static void Main()
{
B b = new B();
b.Display(); // displays class A Display method.
(b as IB).Display(); // displays class A Display method.
(b as AI).Display(); // displays AI.Display
Console.Readline();
}
}
The above example now has an explicit implementation of the interface method display. Notice the slight variation in the method signature -- this is how you declare an explicit implementation, that is used specifically when the object is represented by the interface, in this case (b as AI).
Otherwise, if the method signature matches, it is used automatically (implicitly) as the method for the interface.
What's happening in your situation is that class B is satisfying the IA interface contract through the fact that its inheriting the appropriate IA method implementations from class A.
The way to look at it is this - an interface is a contract (it has no implementation) therefore it simply demands that any implementing class defines all the same members which it defines in the contract.
In your case you have 1 method in your interface Display, your class B is the only class implementing this interface and it doesn't explicitly define an implementation for Display (perhaps this is where your confusion is). However, it is inheriting from A which does define an implementation for it therefore B implements the interface by default.

Why doesn't C# support explicitly implemented virtual methods?

Interface methods in C# can be implemented explicitly, so that their implementation is invoked when an instance is explicitly cast to the interface type. Why is this not also supported on virtual methods of classes?
Although working around the 'multiple inheritance' issue is unique to interfaces, it seems that for every other reason that explicitly implemented members would be useful for interfaces, they would also be useful for virtual methods. A cleaner return-type covariance model springs to mind.
Edit: By request, an example:
public class Foo {
...
}
public class Bar : Foo {
...
}
class Base {
abstract Foo A ();
}
class Dervied {
private Bar _b;
Bar A () {
return _b;
}
Foo Base.A () {
return _b;
}
}
I am aware of using helper methods to simulate this, but the net effect seems to have any of the bad characteristics that explicit implementation would have, but with a dirtier API. The crux of my question is not how to do return type covariance, but why a similar mechanism for interfaces is not supported for virtual methods.
Some people recommend not having public virtual methods in the first place. But instead create one public non virtual method representing the consumer interface, and one protected virtual method representing the implementer interface.
I would not call separating the contracts for caller and implementer "muddying the design". In many cases it's cleaner IMO, but I'm usually too lazy to actually do it that way.
This design works much better with return type covariance and method hiding.
An additional benefit of this is that the public wrapper can add additional checking code and supports different contracts for the caller and implementer.
An example of how I'd emulate return type covariance:
public class Base
{
protected virtual Base FooOverride(int i){return new Base();};//FooOverride does not need to duplicate the argument checking
public Base Foo(int i)
{
if(i<0)
throw new ArgumentException("i<0");
return FooOverride(i);
}
}
public class Derived:Base
{
protected override Base FooOverride(int i){return new Derived();};
public new Derived Foo(int i)
{
return (Derived)base.Foo();
}
}
What benefit would that have, besides from allowing something like this?
class Base
{
virtual void M() { }
}
class Derived : Base
{
override void M() { }
override void Base.M() { }
}
This effectively bakes a violation of the Liskov Substitution Principle into the C# language - if I have a variable of type Base, calling M() on it can do entirely different things depending on whether the run-time type is Base or Derived.
Explicit interface implementation is different. Say you have this:
interface IFoo
{
void DoStuff();
}
interface IBar
{
void DoStuff();
}
class C : IFoo, IBar
{
void IFoo.DoStuff() { }
void IBar.DoStuff() { }
}
This preserves the LSP - if I have an IFoo variable that happens to be of run-time type C, calling DoStuff() on it will get the IFoo implementation of it. Likewise with IBar.

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