Implement interface partially over multiple classes - c#

Is it possible to have an interface with two methods, suppose Add() and Subtract(), and implement the Add() method in class A and the Subtract() method in class B?

You cannot do that. If you are implementing an interface in a class, you have to provide implementation for all the methods in the interface. WCF contracts and services are no exception.

You can do it with inheritance:
public interface IFooBar
{
void Foo();
void Bar();
}
public class Fooer
{
public void Foo()
{
}
}
public class FooBar : Fooer, IFooBar
{
public void Bar()
{
}
}
You can apply the IFooBar interface to the FooBar class, because it implements the Foo() interface method through inheriting the Fooer class.
But in general you don't want to.

Related

How to use an extension method to make an interface complete

Given an interface IFoo
interface IFoo {
void Do();
void Stuff();
}
Let assume there are (legacy) classes Foo1, Foo2, Foo3 all implementing IFoo.
Stuff can be done by using some methods of IFoo, or in case of the newer classes, by just using DoStuff(). Actually, one might look at it as if DoStuff() was "forgotten" on IFoo.
There are also newer Classes FooX (FooY, ...) implementing IFoo2, in additional those has a method DoStuff();
interface IFoo2 : IFoo {
void DoStuff();
}
I need to accept IFoo objects, and be able to "Do Stuff" on it.
//Let us assume foos = new IFoo[] {new Foo1(), new Foo2(), new Foo3(), new FooX()};
void MyMethod(IFoo[] foos){
foreach(foo in foos){
//DoStuff is not defined in IFoo
foo.DoStuff();
}
}
So, I thought to just define an extension method DoStuff() on IFoo for the legacy classes
public static DoStuff(this IFoo self){
self.Do();
self.Stuff();
}
Unfortunately, this extension method is always called, even for FooX.
I Could do something like
public static DoSomeStuff(this IFoo self){
if(self is IFoo2) {
(self as IFoo2).DoStuff()
} else {
self.Do();
self.Stuff();
}
}
void MyMethod(IFoo[] foos){
foreach(foo in foos){
foo.DoSomeStuff();
}
}
However, the method MyMethod reside in a legacy project, currently not yet aware of IFoo2. Is it possible to find a solution without using IFoo2?
You shouldn't extend IFoo interface, like that. It's break Interface Segregation principle.
If these object represents exactly the same entity in your code you shouldn't use different interfaces for them.
You might create extension method if you want extend functionality of classes which implements interface IFoo, but don't create second interface which represents the same contract. However if you want to change IFoo contract - refactor legacy objects (add missing implementation).
As long as your variable has the type IFoo, the extension method DoStuff will be called. The usual way of solving this is exactly what you propose in your last paragraph, or ensuring that you use IFoo2 instead of IFoo in places where you want the newer interface method to be called.
You can create an abstract subclass that implements the methods Do and Stuff for the classes that at the current time don't implement it.
public abstract class abstractFoo : IFoo
{
public virtual void Do() {}
public virtual void Stuff(){}
}
If you can then inherit from this abstract class
public class Foo: IFoo
{
// interface implementation required
}
becomes:
public class Foo: abstractFoo
{
// interface implementation NOT required
}
IMHO FooX shouldn't be implementing IFoo to begin with and some reconsideration should be made of your current arquitecture.
That said, and not knowing exactly what limitations you are fighting against, could you send the IFooXs through a wrapper? Something like the following:
public class FooXWrapper<T>: IFoo where T: FooX
{
readonly T foo;
bool doCalled;
public FooWrapper(T foo)
{
this.foo = foo;
}
public void Do()
{
doCalled = true;
}
public void Stuff()
{
if (!doCalled)
throw new InvalidOperationException("Must call Do");
foo.DoStuff();
}
}
Its an ugly hack, but given the circumstances...

How to to implementing only one methods from abstract class out of two abstract methods in C#?

In an Abstract class there are two abstract methods Method1() and Method2(),
but I like to inherit only one Method1() in derived Class, how to handle the situation?
public abstract class BaseClass
{
public abstract void Method1();
public abstract void Method2();
}
Really you can't... If you have to (and I would really question the reasons) some options are:
If you do not have any control over the abstract classes involved, and must use this specific abstract class, then, only way is to make the implementation in derived class throw a NotImplementedException.
public MyDerivedClass: BaseClass
{
public override void Method1()
{
// implementation of Method1
}
public override void Method2()
{ throw new NotImplementedException(); }
}
... or create another abstract base class called, say OnlyDOMethod1
public abstract class OnlyDoMethod1
{ public abstract void Method1(); }
then, modify Baseclass so it inherits from OnlyDoMethod1
public abstract class BaseClass: OnlyDoMethod1
{ public abstract void Method2(); }
and use OnlyDoMethod1 anywhere you only want Method1
public MyDerivedClass: OnlyDoMethod1
{
public override void Method1()
{
// implementation of Method1
}
}
It sounds like what you're looking for is interfaces. Something like this:
public interface ICanDoMethod1
{
void Method1();
}
public interface ICanDoMethod2
{
void Method2();
}
Then in your classes you can selectively implement them:
public class JustMethod1 : ICanDoMethod1
{
// implement Method1 here
}
public class Both : ICanDoMethod1, ICanDoMethod2
{
// implement both here
}
// etc.
Essentially, any given class either can or can not be polymorphically interpreted as any given type. If you want to be only part of a type, then what you really have is two types. C# is single-inheritance, so to implement multiple types you would use interfaces.
Conversely, you could also chain your inheritance. Something like this:
public abstract class Base1
{
public abstract void Method1();
}
public abstract class BaseBoth : Base1
{
public abstract void Method2();
}
public class JustOne : Base1
{
// only implement Method1 here
}
public class Both : BaseBoth
{
// implement both here
}
That'll work if the options stack, that is if you don't want to be able to pick and choose and either want "1" or "1 and 2" (but not just "2").
As a last resort, you can "selectively implement" methods by explicitly not implementing the others. It would looks something like:
public class JustOne : BaseClass
{
public override void Method1()
{
// implement
}
public override void Method2()
{
throw new NotImplementedException();
}
}
But this would be something of an anti-pattern, where your objects would advertise functionality that they intentionally do not support. This would mean that the type BaseClass should be considered very unstable/unreliable, because there's no way for anything consuming that type to know how it should actually behave.
Ultimately, it sounds like you've painted yourself into a corner with your types and you need to back up a little and re-think them. Liskov Substitution shouldn't be taken so lightly.
This is basic example of violation of one of SOLID principles Interface segregation principle
A client should never be forced to implement an interface that it
doesn’t use or clients shouldn’t be forced to depend on methods they
do not use
If you have abstraction where you need only some of method you need to split them in separated abstractions.
.NET do not support multi-inheritance from classes, nut have nice workaround for this problem -> interfaces.
If you care about your code, then you have only one option - split abstract class into two separated classes which have only one method.
If you work only with abstraction then interfaces is better approach, because you can implement multiply interfaces in one class.
public interface IMethodOne
{
void Method1();
}
public interface IMethodTwo
{
void Method2();
}
Then you can implement that both interfaces in the class which needs both methods. And use only one interface in the class with one method needs.
public abstract class BaseClass : IMethodOne, IMethodTwo
{
public abstract void Method1();
public abstract void Method2();
}
And class with one method
public abstract class BaseClassOneMethod : IMethodOne
{
public abstract void Method1();
}

Is it possible to call the explicit interface implementation of the base class in c#?

I would like this program to compile, and then print the output below:
public interface IFoo
{
void Bar();
}
public class FooBase : IFoo
{
void IFoo.Bar()
{
Console.WriteLine("Hello from base class.");
}
}
public class Foo : FooBase, IFoo
{
void IFoo.Bar()
{
(base as IFoo).Bar(); // doesn't compile
Console.WriteLine("Foo added some behavior!");
}
}
public static class Program
{
public static void Main(string[] args)
{
var foo = new Foo() as IFoo;
foo.Bar();
}
}
Desired output:
Hello from base class.
Foo added some behavior!
Obviously, the code above doesn't compile, because it's an invalid way to use the base keyword. Is there a way to accomplish this, without changing the implementation in the base class to a non-explicit one?
You can simply have the explicit interface implementation in the base class call a protected method in the class for its implementation. This allows other derived classes to still call that protected method while still explicitly implementing the interface (and also not publicly exposing the interface's method through the type itself, which presumably is the actual goal).

Explicitly implementing an interface with an abstract method

Here is my interface:
public interface MyInterface {
bool Foo();
}
Here is my abstract class:
public abstract class MyAbstractClass : MyInterface {
abstract bool MyInterface.Foo();
}
This is the compiler error:
"The modifier 'abstract' is not valid for this item.
How should I go on about explicitly implementing an abstract with an abstract method?
You can't, basically. Not directly, anyway. You can't override a method which is explicitly implementing an interface, and you have to override an abstract method. The closest you could come would be:
bool MyInterface.Foo() {
return FooImpl();
}
protected abstract bool FooImpl();
That still implements the interface explicitly and forces derived classes to actually provide the implementation. Are those the aspects you're trying to achieve?
You have to use an implicit implementation of the interface member instead of an explicit implementation:
public abstract class MyAbstractClass : MyInterface
{
public abstract bool Foo();
}
In fact there is another option than using an abstract helper method which still keeps the implementation private:
public abstract class MyAbstractClass : MyInterface
{
bool MyInterface.Foo() // must be overridden
{ throw NotImplementedException(); // never called
}
}
public class MyDerivedClass : MyAbstractClass, MyInterface
{
bool MyInterface.Foo() // overrides MyInterface.Foo
{ // Place your implementation here
}
}
This pattern will also work if the interface has many methods and only some of them are redefined in the derived class. And, of course, you can also use this to override private interface implementations in general.
The major disadvantage is that Foo cannot be declared abstract in MyAbstractClass, so the compiler cannot ensure that the method is actually overridden. (It's a pity that abstract classes may not have incomplete interface implementations in C#.)
The advantage is that you save one calli instruction that is likely to cause CPU pipeline stalls. However, the impact is quite small, since the method cannot be inlined anyway because of the interface call. So I would recommend it only for performance critical cases.
I'm not sure why you need to. Why not let the concrete implementation of the abstract class implement the member from the interface? It's the same thing really.
An abstract method has no implementation, so it can't be used to explicitly implement an interface method.
I am able to do this
public interface SampleInterface
{
void member1();
void member2();
void member3();
}
public abstract class Client2 : SampleInterface.SampleInterface
{
public void member1()
{
throw new NotImplementedException();
}
public abstract void member2();
public void member3()
{
throw new NotImplementedException();
}
}
public class Client3 : Client2
{
public Client3()
{
}
public override void member2()
{
throw new NotImplementedException();
}
}
In addition to Jon's explanation: this is a way to bypass the problem instead of solving it directly and will work only in certain circumstances, but maybe someone will benefit from this idea.
If you plan to pass all (or at lest most) interface method calls to the derived class, you can do it in the following way:
public interface MyInterface
{
bool Foo();
}
public abstract class MyAbstractClass
{
public abstract MyInterface AsMyInterface();
}
public class MyDerivedClass : MyInterface
{
public override MyInterface AsMyInterface()
{
return this;
}
public bool Foo()
{
return false;
}
}
...
MyAbstractClass c = new MyDerivedClass();
MyInterface i = c.AsMyInterface();
bool b = i.Foo();
Abstract all the interface methods that are implemented in a abstract class, even if you do not use them.
This particular case requires that you are implementing a hierarchy of 2 or more abstract classes, with a interface.
I was trying to implement a hierarchy in C# as well. I needed a Interface but I wanted a Abstract class, because most of the properties are the same for the interface. To do this I had to create a separate Abstract class, with the implementation, and then my Concrete classes, or in my case another abstract class, would inherit the Interface and the Abstract Class.
I do not think that this first one is a good example for many reasons, but I had to have it because the compiler would not allow FooBar to implement Foo and then have another abstract class to inherit FooBar. So I had a abstract class with a abstract method bar(), and the interface with the bar() method.
public interface Foo {
bool bar();
//other stuffs
}
public abstract class FooBar {
public abstract bool bar();
//Other stuffs
}
public abstract class FooBarAbstraction: FooBar, Foo {
//other stuffs
//Don't supply the interface and abstract here
}
public class FooBarConcrete: FooBarAbstraction {
public override bool bar() {
return true;
}
//other stuffs
}
This was my first attempt, then I got curious and started to think about it. I came across this solution. The better solution.
public interface Foo {
bool bar();
bool buzz();
//other stuffs
}
public abstract class FooBar : Foo{
public abstract bool bar();
public abstract bool buzz();
//Other stuffs
}
public abstract class FooBarAbstraction: FooBar {
//other stuffs
//Don't supply the interface and abstract here
// override everything else
public override bool buzz() {
return false;
}
}
public class FooBarConcrete: FooBarAbstraction {
public override bool bar() {
return true;
}
//other stuffs
}

How to force sub classes to implement a method

I am creating an object structure and I want all sub classes of the base to be forced to implement a method.
The only ways I could think of doing it were:
An abstract class - Would work but the base class has some useful helper functions that get used by some of the sub classes.
An interface - If applied to just the base class then the sub classes don't have to implement the function only the base class does.
Is this even possible?
N.B. This is a .NET 2 app.
You can have abstract methods in a class with other methods that are implemented. The advantage over an interface is that you can include some code with your class and have the new object be forced to fill in the details for the abstract methods.
public abstract class YourClass
{
// Your class implementation
public abstract void DoSomething(int x, int y);
public void DoSomethingElse(int a, string b)
{
// You can implement this here
}
}
An abstract class - Would work but the
base class has some useful helper
functions that get used by some of the
sub classe
An abstract class doesn't require all functions it provides to be abstract.
abstract class Base {
public void Foo() {} // Ordinary method
public virtual void Bar() {} // Can be overridden
public abstract void Xyz(); // This one *must* be overridden
}
Note that if you replace public with protected, the marked method will be only visible to base classes and subclasses.
An interface - If applied to just the
base class then the sub classes don't
have to implement the function only
the base class does.
This is not entirely correct. If the base class is abstract, you can mark methods that belong to the interface as abstract, and force the implementation in the subclasses.
That brings an option you didn't mention: to use both. You have an IFoo interface, and a FooBase abstract base class the implements it, or part of it. This provides subclasses with a "default" implementation of the interface (or part of it), and also lets you inherit from something else and still implement the interface, or if you want to implement the interface but not inherit the base class implementation. An example might help:
// Your interface
interface IFoo { void A(); void B; }
// A "default" implementation of that interface
abstract class FooBase : IFoo
{
public abstract void A();
public void B()
{
Console.WriteLine("B");
}
}
// A class that implements IFoo by reusing FooBase partial implementation
class Foo : FooBase
{
public override void A()
{
Console.WriteLine("A");
}
}
// This is a different class you may want to inherit from
class Bar
{
public void C()
{
Console.WriteLine("C");
}
}
// A class that inherits from Bar and implements IFoo
class FooBar : Bar, IFoo
{
public void A()
{
Console.WriteLine("Foobar.A");
}
public void B()
{
Console.WriteLine("Foobar.B");
}
}
Yes, and if all the classes you need to do this for are logically subclasses of an existing abstract base class, then add an abstract method to the base class... This is better than an interface because it allows you to add implementation later (by changing abstract base class method to virtual method with a default implementation), if/when it turns out that, say, eight of ten derived classes will have the same implementation, and say, only two of them differ...
EDIT: (based on thread in comments below) The base class must be declared as abstract to do this... You can't have an abstract method in a non-abstract class because a non-abstract class can be instantiated, and if an instance of it was created, there wouldbe NO implementation for that method. So this is illegal. By declaring the base as abstract, you inhibit instantiation of the class. Then, only non-abstract derived classes can be instantiated, where, (because the base method is abstract) you MUST add an implementation for that method.
And full worker sample with params (.netcore 2.2):
class User{
public string Name = "Fen";
}
class Message{
public string Text = "Ho";
}
// Interface
interface IWorkerLoop
{
// Working with client message
string MessageWorker(string msg);
}
// AbstractWorkerLoop partial implementation
public abstract class AbstractWorkerLoop : IWorkerLoop
{
public User user;
public Message msg;
// Append session object to loop
public abstract AbstractWorkerLoop(ref User user, ref Message msg){
this.user = user;
this.msg = msg;
}
public abstract string MessageWorker(string msg);
}
// Worker class
public class TestWorkerLoop : AbstractWorkerLoop
{
public TestWorkerLoop(ref User user, ref Message msg) : base(user, msg){
this.user = user;
this.msg = msg;
}
public override string MessageWorker(string msg){
// Do something with client message
return "Works";
}
}

Categories

Resources