What I have is a non generic interface for the purpose of having a common contact that I can call functions. The interface returns objects which implement other interfaces. For example:
public interface ISearchAdvancedInputController
{
ISearchAdvancedInput GetAdvancedInput();
void LoadFromModel(ISearchAdvancedInput advancedInput);
}
I then currently have an abstract generic class which implements the interface but imposes requirements of the type. The types of the abstract class must implement the same interfaces as the interface's properties and functions demand. I cast the generic type to the implemented type when necessary so that I can satisfy the requirements of the implemented non abstract interface. This way, I can extend this abstract class and it will enforce type requirements across a larger class w/ many different types used across it. For example:
public abstract class ISearchAdvancedInputControllerBase<standardInput, advancedInputType> : ISearchAdvancedInputController
where advancedInputType : ISearchAdvancedInput
{
protected abstract advancedInputType GetAdvancedInput();
ISearchAdvancedInput ISearchAdvancedInputController.GetAdvancedInput()
{
return GetAdvancedInput();
}
void ISearchAdvancedInputController.LoadFromModel(ISearchAdvancedInput advancedInput)
{
LoadFromModel((advancedInputType)advancedInput);
}
public abstract void LoadFromModel(advancedInputType advancedInput);
}
This works really well in general however it falls short because I'm having to use an abstract CLASS in order to perform this overriding. As such when I want to actually make use of it for more concrete examples, I encounter the error that I can only extend a single class.
So to get around this I extend the "other" class in the previous base abstract class. However this is not ideal because if I wind up creating another concrete implementation I need to redefine all of the type translations that I'm doing which is NOT related to the concrete classes implementation.
What I'd like is to not have an abstract class but instead some sort of abstract interface. If I had this I'd be able to implement concrete classes more succinctly. I've looked at other instances of this question and have tried what seems to be the main suggestion which is to make the initial interface generic and have the type extend the resulting interface type and then extend that interface with the more abstract interface as such:
interface TestGenericInterface<a> where a:TestClassInterfaceA
{
TestClassInterfaceA testGeneric { get; }
}
interface TestGenericComplexInterface<a> : TestGenericInterface<a>
where a:TestClassInterfaceA
{
new a testGeneric { get; }
}
However the concrete class seems to suffer from the same issue that's shown when you start from a non generic interface where each function / property of the base interface needs overwritten.
public class TestClass : TestGenericComplexInterface<TestGC>
{
public TestGC testGeneric => I want to complete this because its return is the type that I'm wanting to use for this concrete implementation
TestClassInterfaceA TestGenericInterface<TestGC>.testGeneric => I don't want to have to complete this because this function is already handled by the previous function in a round about sense.
}
public class TestGC : TestClassInterfaceA { }
I do see a note that I could provide default implementation of functions if I use c# v8.0 or greater, so I must be on a version prior to that but I figure this should be possible w/o that, but maybe in a different way. Hope ya'll can assist.
My question is, In C# If I want to add an another Function in a Interface but I don't want to Implement that function in all classes that are implementing that interface. How can I achieve that ? For example
A interface contain 5 methods and that interface is implemented in 20 Classes. Now I would like to add another method in same interface but I want to implement that function in only 5 Classes and not In 15 classes ? How could I achieve that ?
Thanks
public interface IWidelyUsed { ... }
This is the one implemented by those 20 classes
public interface IParticularCase : IWidelyUsed { ... }
This will have the other function
Short answer: split the big interface definition into two more specialized ones.
Some theory behind it:
Interface segregation principle as a part of SOLID
This contradicts the very essence of what an interface is. If an interface IBlob defines void DoAThing(), it means that any class that implements it knows how to Do A Thing. That's the contract. If you want some of your Blobs to be able to Do A Thing and some don't, you're essentially saying that Doing A Thing isn't a feature of Blobs.
Now, there are some cases where you do want all IBlobs to expose DoAThing, but you don't want anything to happen there. You want a default, null implementation. For these cases, we can add an abstract base class between the concrete classes and the interface:
interface IBlob
{
void DoAThing();
}
abstract class AbstractBlob : IBlob
{
virtual void DoAThing() { } // nothing happening.
}
class BlobThatDoesThings : AbstractBlob
{
override void DoAThing() { DoSomething(); }
}
class RegularBlob : AbstractBlob
{
// Inherits the abstract blob's implementation.
}
In other cases, though, where you really only need some blobs to implement a method, use the interface specialization method that BlackBear mentioned in his answer.
This question already has answers here:
Why is a base class in C# allowed to implement an interface contract without inheriting from it?
(2 answers)
Closed 10 years ago.
In my project I've found a strange situation which seems completely valid in C#, because I have no compilte-time errors.
Simplified example looks like that:
using System;
using System.Collections.Generic;
namespace Test
{
interface IFoo
{
void FooMethod();
}
class A
{
public void FooMethod()
{
Console.WriteLine("implementation");
}
}
class B : A, IFoo
{
}
class Program
{
static void Main(string[] args)
{
IFoo foo = new B();
foo.FooMethod();
}
}
}
Such code compiles. However, note that A is not IFoo and B doesn't implement IFoo methods. In my case, by accident (after refactoring), A has the method with the same signature. But why should A know how to implement the FooMethod of the IFoo interface? A even doesn't know that IFoo exist.
For me having such design is dangerous. Because every time I implement some interface I should check if each method in this interface "interferes" with the base class methods.
If this is "pure C# feature"? What is it called? Am I missing something?
For each member in the interface, the compiler simply looks for an explicit implementation (if one), then a public implementation (implicit implementation), i.e. a method on the public API that matches the interface signature. In this case, A.FooMethod() looks like a fine match for a public implementation. If B wasn't happy with that selection, it could either new the method, or use an explicit implementation; the latter would be preferred:
void IFoo.FooMethod() { /* explicit implementation */ }
The key word here is implements. Your base class, although it doesn't know anything about IFoo the method signature has been declared which implements the method in your interface somewhere in your class hierarchy.
So when you implement IFoo in the derived class, it already has the method signature implemented within the class structure so therefore doesn't need to implement it again.
If you had this:
interface IFoo
{
void FooMethod();
}
class A
{
private void FooMethod(){}
}
class B : A, IFoo
{
}
You need to implement IFoo in this case because the IFoo structure isn't accessible at the point where it is implemented, and as Mark says. You can implicitly implement the interface by doing IFoo.FooMethod() to ensure that you have an implementation despite having an appropriate method signature already defined in the hierarchy.
You say in a comment,
how likely that the one who wrote implementation of FooMethod in A class which doesn't implement IFoo actually meant to implement IFoo?
Well, it doesn't matter what the writer of A thought at the time of A's creation. It's the writer of B who must take responsibility for the fact that B both inherits from A AND implements IFoo. It is up to the author of B to think about the consequences of the definition of B.
You also say
In my case by accident (after refactoring) A has the method with the same signature
suggesting that this situation came about after A and B had both been written. In that case, the situation changes: When editing a class which is *inherited from * (such as A), it is the editor's responsibility to check the effects of the edit on all inheriting classes.
To implement an interface, a class needs only to (a) declare that it is implementing that interface (such as your class B does), and (b) provide implementations for all the methods defined in the interface, either directly or indirectly via a base class (such as your class B does).
Section 13.4.4. of the C# specification states:
Interface mapping for a class or struct C locates an implementation for each member of each interface specified in the base class list of C. The implementation of a particular interface member I.M, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located:
So it seems that this is well defined behavior, as the correct implementation of the FooMethod is not found in B, so a search is performed on its base class A where a method with matching signature is found. This is even explicitly pointed out in the same section of the spec:
The members of a base class participate in interface mapping. In the example
interface Interface1
{
void F();
}
class Class1
{
public void F() {}
public void G() {}
}
class Class2: Class1, Interface1
{
new public void G() {}
}
the method F in Class1 is used in Class2's implementation of Interface1.
The feature is called inheritance. And if you don't like the design, just don't use it. A lot of people dislike inheritance, so you might, either. The definition of inheritance is, that all the members of the base class are also members of the derived one. So there isn't any compiler error. Therefore the Derived implements the contract IFoo provides. It's the base class member, which fulfills this requirement.
The beauty of it is, that you can implement an interface through a base functionality (virtual), which can be overriden if a Derived is expected to behave differently.
Interfaces are not inherited, interfaces are implemented. Thus when you derive a class from an interface, it means
hey interface, you will find a method here which implements the method
signiture you have provided.
Since the base class has an implementation of the method, with the same method signiture defined in the interface, there will be no problems.
Even if you write a second interface with including the same method signiture it will still work.
interface IFoo2
{
void FooMethod();
}
class B : A, IFoo, IFoo2
{
}
"But why should A know how to implement the FooMethod of the IFoo interface? A even doesn't know that IFoo exist."
A doesn't need to know about existence of interface IFoo. Its not A's responsibility to implement FooMethod correctly. Apparently A happened to implement the method which has same signature that of IFoo interface method FooMethod.
Its the responsibility of B to implement FooMethod since it is implementing IFoo interface. But since B is already having a method named FooMethod (inherited from A), it does not need to implement it explicitly. If an inherited method is not doing its job, B can new the method and write its own implementation.
B do implement IFOO. B inherits from A so it actually looks like this:
class B : IFoo //Notice there is no A here.
{
public void FooMethod()
{
Console.WriteLine("implementation");
}
}
And it is clear (from the above code) that B is implementing the IFoo and nothing is special.
While it is not particularly helpful to speculate as to why the creators of C# did what they did, and while I do not like this particular feature, I suspect part of the reason it works as it does is that there is no other good syntax to specify that an interface should be implemented by an already existing base-class method. Requiring that the derived class must define methods that do nothing but chain to the base-class implementation would seem ugly.
That having been said, I think it would have been cleaner for C# to resolve that general problem (interface methods that chain to other members are ugly) by providing a syntax to explicitly attach an interface member to a class member, than use auto-binding semantics to handle one particular situation but require chaining in a more common situation (implementation of interface by protected virtual method):
protected virtual IFoo_Method(int a, int b, int c)
{ ... }
IFoo.Method(int a, int b, int c)
{ IFoo_Method(a,b,c); }
While the JITter may be able to figure out that the IFoo_Method call should be in-lined, it really shouldn't have to. It would seem cleaner to declare that the protected method IFoo_Method should be regarded as the implementation of IFoo.Method.
I have a Generic Interface
public interface TheInterface<T> where T : IObject
I also have an object class that this interface works with
public class SomeObject : IObject
I then have a class that implements the interface
public class ClassThatWorksWithSomeObject : TheInterface<SomeObject>
This all works well enough. Later on I add a class that works with TheInterface class independent of what version of IObject he uses.
public class IDoStuffToInterface
{
public IDoStuffToInterface(TheInterface<IObject> interface)
{
//bla bla
}
}
Problem is I can't pass ClassThatWorksWithSomeObject in there, even if It inherits from the intreface and it's generic object inherits from IObject.
I guess there are some cases that it could be hurtful if it did, but I can't think of any.
Is there a way to do this better?
I don't know the detail impelmentation, you can try:
public interface TheInterface<out T> where T : IObject
if you are using C#4.0
I think what you're doing should work, but you may need to use the covariance and contravariance keywords.
You need to make you definition of TheInterface covariant so that it accepts the wider types of IObject:
public interface TheInterface<out T> where T : IObject
You should be able to do this in C#4.0 by marking the interface type as contravariant, but I think you can also get around this by making the IDoStuffInterface generic as well.
public class IDoStuffToInterface<T> where T : IObject
{
public IDoStuffToInterface(TheInterface<T> interface)
{
//bla bla
}
}
Since SomeObject qualifies for T and ClassThatWorksWithSomeObject implements TheInterface<SomeObject>, it should be acceptable as a parameter.
The other way I saw mentioned by tvanfosson was to make your IDoStuffToInterface class generic. That would work nicely as well, if (as it appears in the example) the TheInterface is being passed into the constructor and (presumably) stored in the class.
However, if it were just a function (or even a constructor) that uses the TheInterface and it isn't being stored in the class, it would probably be better to make the function itself generic and leave the class alone. For example:
public class IDoStuffToInterface
{
public void DoSomething<T>(TheInterface<T> theInterface) where T : IObject
{
//bla bla
}
}
This would allow you to do the following:
ClassThatWorksWithSomeObject myObject = new ClassThatWorksWithSomeObject();
IDoStuffToInterface actor = new IDoStuffToInterface();
actor.DoSomething(myObject);
That compiles without any problem because the compiler is able to tell by inference that you are actually calling
actor.DoSomething<SomeObject>(myObject);
Now, I think that using covariance is still probably the best option if you are in control of the interface definition. But I wanted to add this as another option for when you don't have that degree of control in your interface.
I would like to only implement certain interfaces within other interfaces, I don't want them to be able to be inherited directly by a class.
Thanks in advance!
You can't do this in C# - any class can implement any interface it has access to.
Why would you want to do this? Bear in mind that by declaring an interface inheritance:
public interface InterfaceA {}
public interface InterfaceB : InterfaceA {}
You're specifying that anything implementing InterfaceB also has to implement InterfaceA, so you'll get classes implementing InterfaceA anyway.
First of all, it doesn't make sense to say "implement within other interfaces" because interfaces can't implement anything.
I can see two flawed ways of doing this, sort of.
Make Animated and NonAnimated abstract classes that implement IAnimation. The concrete class below them can still forcibly override your IAnimation methods with the new operator:
class SomeAnim : Animated
{
public new void Foo() { }
}
Use mixins. Keep IAnimated and INonAnimated as interfaces, but don't put any methods in your interface. Instead define extension methods like this:
static class Ext
{
public static void Foo(this IAnim anim)
{
if (anim is IAnimated) // do something
else if (anim is INonAnimated) // do something else
}
}
again, a bit of a hack. But what you're trying to do indicates design flaws anyway.
The best I can suggest is to put them -- both the top level and the descended interfaces, in a separate assembly, with the base-level interfaces declared as internal, and the interfaces which extend those interfaces as public.