Add function to Interface without implementation in all classes - c#

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.

Related

Can I override the properties and functions of a generically typed interface extending a non generic interface to consider generic type(s) in C#

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.

Can we use Abstract class instead of interface [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 7 years ago.
i have started career as support developer but i have dream to get a job for S/W dev.
i am learning OOPS with C#. often one thing bug me that is interface and abstract class usage. when to use interface and when to use abstract class. i search google on this topic but whatever the answer i browse and i saw all people try to explain what is abstract and interface but i am not after their definition rather i want see their real usage in real world program. here i like to highlight one code where interface is used but i think the full things can be design with abstract class too.
see the below code of repository design pattern where interface has been used
if i expose repository as interface
public interface IEmployeeRepository
{
Employee[] GetAll();
}
then advantage will be i could have as many implementations as i like as below
public class EmployeeRepositoryEF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying your EF DbContext
}
}
public class EmployeeRepositoryXML: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying an XML file
}
}
public class EmployeeRepositoryWCF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying some remote WCF service
}
}
see the above code which has one contract method GetAll()
and who ever will extend the interface then they can provide their own implementation. that is the advantage but my question can i write abstract class instead of interface here ?
suppose i have one abstract class
abstract class AbsEmployeeRepository
{
abstract public Employee[] GetAll();
}
now my all other repository will extend the abstract class AbsEmployeeRepository
and override the function GetAll() to give their own implementation.
now the question is if abstract class can solve my purpose then why we need interface in this scenario. where multiple inheritance is concern then interface will be preferred other wise we can complete job with abstract class.
looking for valuable comments and suggestions. thanks
You would use an abstract class, when you have
Code to be shared.
Default behaviour in methods, but want users of your class to be able to override it.
You would use an interface when
There is no shared code.
It needs to be applied to many objects, with no common base class.
To make the definitions of public methods clearer and provide documentation.
You wish the source code to be private.
Often you would use an abstract class (for shared code) together with an interface (for documentation).
Interface provides only "description" of your future classes, while abstract classes used when you need to have some "unfinished functionality". So if you want to have a class with some logic provided and some unimplemented functions - you should use abstract class, but if all the functions is not implemented - use interface instead.
You should use an abstract class IF all your implementation share a common code basis implementation. That means, the interface will guarantee, that all classes have the same members, but each one must have its own implementation for them.
If you have an abstract class as base, all inheriting classes share the same implementation unless they override it, which is in many cases not needed, often you need to implement only a hand full of members differently.
Interface - guarantee same members.
Abstract class - share common code basis.
Some nice thoughts about it got mentioned on my question for this, maybe this helps you out.
You use abstract classes when you need to provide more than just abstract members to implement but also some concrete member:
public abstract class A
{
protected abstract void DoSomeCheck();
public void DoStuff()
{
// You don't know how DoSomeCheck will be implemented but
// you know a derived class must implement it
DoSomeCheck();
}
}
Alternatively, you use interfaces to define contracts that must be fulfilled by implementers in order to ensure that they can work together with your code:
// This car accepts any engine that implements IEngine
public class Car
{
public IEngine Engine { get; set; }
}
public interface IEngine
{
void Start();
}
There're many other use cases for both abstract classes and interfaces, but covering them would require a to compose a book instead of a simple answer. I still think that above explanation should give you the required hint to learn more about the topic.
can i write abstract class instead of interface here ?
Technically, yes you can. Practically, you shouldn't.
In this particular case implementation of the repositories is likely to be different. If implementation is different, an interface will declare desired behaviour in a clear way. Use of an abstract class can be justified, if the implementation was the same for all your repositories, or some methods where the same. Therefore allowing you to move otherwise duplicated code into one shared place.
In your particular case I'd rather not use either tailored interface or abstract class. There's IEnumerable<T> that does all you want, do not re-invent the wheel:
public class EmployeeRepositoryEF: IEnumerable<Employee> {
...
}
public class EmployeeRepositoryXML: IEnumerable<Employee> {
...
}
whenever you want an array all you need do is ToArray():
EmployeeRepositoryEF myRepo = ...
Employee[] staff = myRepo.ToArray(); // <- just ask for array

What to use here, abstract class or Interface? [duplicate]

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 8 years ago.
I have an abstract class say CTest which contains only the abstract method f1() and nothing else. Similiarly, i have a Interface ITest with the only method f1(). Here both the CTest abstract class and ITest interface does the same thing.
The one difference is that, the Interface provides the flexibility that it can be implemented in any classes which already derived from other class but abstract classes cannot.
Apart from the above difference, What is the actual difference between these two? and which one is efficient here(CTest or ITest)? When i should use what? Any specific scenario's in OO Design and any general suggessions on this are helpful
Other than inheritance, it depends on the scenario. Check this code project article with an excellent example.
[From the article]
Lets Assume you need to make three classes, first is CAR, second is
MAN, third is WOMAN. Now you need a function in each of them to define
how they Move. Now all three can move but CAR moves entirely in
different way than MAN and WOMAN. So here we use an Interface
IMOVEMENT and declare a function MOVE in it. Now all three classes can
inherit this interface. So the classes goes like this.
public interface IMovement
{
void Move();
}
public class Car : IMovement
{
public void Move()
{
//Provide Implementation
}
}
public class Man : IMovement
{
public void Move()
{
//Provide Implementation
}
}
public class Woman : IMovement
{
public void Move()
{
//Provide Implementation
}
}
But, since MAN and WOMAN walk in similar way, so providing same
behavior in two different methods will be code redundancy, in simpler
words code is not re-used. So we can now define a Abstract Class for
Human Beings movements, so this class can be HUMANBEINGMOVEMENT. Also
the same can be applied to CAR class, since there are lot of
manufactures for cars and all cars move in similar way so we can also
define a abstract class for Cars movement which can be CARSMOVEMENT.
So our refactored code will be .
public interface IMovement
{
void Move();
}
public abstract class CarsMovement : IMovement
{
public virtual void Move()
{
//default behavior for cars movement
}
}
public class SuzukiCar : CarsMovement
{
public override void Move()
{
//Provide Implementation
}
}
public abstract class HumanBeingMovement : IMovement
{
public virtual void Move()
{
//default behavior for human being movement
}
}
public class Man : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}
public class Woman : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}
In Java prefer Interfaces to Abstract Classes. Refer Item 18 in Effective Java
Main Points :
Existing classes can be retroffited to implement a new interface.
Interfaces are ideal for defining mixins.
Interfaces allow the construction of nonheirarchical type frameworks.
Interfaces enable safe, powerful functionality enhancements.
in c# it allows only single level inheritance. therefore interfaces can be use to do multiple inheritances
and also for more details :
http://www.dotnetfunda.com/forums/thread4085-difference-between-interface-and-abstract-class.aspx
http://sadi02.wordpress.com/2008/05/08/what-is-difference-in-an-abstract-class-and-an-interface/
For me it better to use interface here. Abstract class should be used when you could extract some code there (you could implement method or there is other stuff that want to invoke it).
In this case there is no difference but CTest class has the only class which could be inherited as a Class . However ITest interface can be inherited by other class and interface at the same time.
In the scenario you have mentioned, that there is only one method, which will have no definition, the best way to go for is interface.
The major advantage an interface gives in Java that you can implement more than one interfaces, but you can extend only one class. So if you are already extending the one abstract class, you are not left with an option of extending any other class.
Golden rule: Interface is better than abstract class if we only need
to define methods and not declare them.
Having said that an interface is better in your case, a programmer should also think of his code from a future perspective. Do you feel the class/ interface you are creating will have more methods in future. Would you like to define those methods or just declare? Answer to these question will let you know if an interface is sufficient or will need an abstract class.
Advantage:
Implementation of Abstract class is better than Interface because method looking up of abstract class is fast than interface. If you modify your interface , you have to update your implementation class but any modification of abstract class , no effect on implementation class.
disadvantage:
If you want to implement more than one parent class method , it is not possible.
But regarding to interface you can implement more than one.
In this case, and assuming that your Abstract Class will only contain abstract methods, you should, in my opinion, go with the Interface. Abstract classes with abstract methods and interfaces serve the same purpose, however, you can extend only one class but implement as many as you want, thus making your code less prone to significant changes should you decide the inherit some functionality from some other class.
Regarding your question: But What is the actual difference between these two? and which one is efficient here(CTest or ITest)? When i should use what? Any specific scenario's in OO Design and any general suggessions on this are helpful
Interfaces are similar to contracts, when a class implements an interface, it guarantees an implementation. This is usually helpful when someone wants to provide functionality but does not want to reveal internal code, so the developer will just throw out the interface so that you can make your calls without knowing how is each method implemented. You can obviously implement as many interfaces as you like.
Abstract classes allow you to create a class which has certain behaviours which are specified and some others which are left to be implemented in the future. Unlike interfaces however, each class can only extend one class, so you should extend classes with caution from this point of view. Abstract classes also allow you to inject behaviour to one class and have it automatically spread through its child classes. This usually makes certain sections of development/maintenance easier.

Allowing implementing interface only for specific classes

Is it possible to permit only some specific classes to implement an iterface?
Let's say that I created interface IMyInterface and I want only classes which derive from UserControl to have an ability to implement my interface. Is this possible?
You cannot, but you can achieve something similar by adding a Control property to your interface, and by-convention making all the implementations return this. Doesn't solve your problem, but makes the implementer think a bit whether or not the interface really belongs there. Also allows the user of the interface to retrieve the control in a type-safe manner without casting.
interface IMyInterface
{
void Foo();
UserControl Control { get; }
}
class MyControl : UserControl, IMyInterface
{
public void Foo()
{
// TODO: Write code here
}
UserControl IMyInterface.Control
{
get { return this; }
}
}
UPDATE
There is also another solution - making a generic method. The interface itself will not be restricted, but the method operating will be. For example, the following method requires that its parameter both inherits UserControl and implements IMyInterface:
void Bar<T>(T item)
where T : UserControl, IMyInterface
{
item.Width = 120; // user control property
item.Foo(); // IMyInterface method
}
I realize this is an old post, but I had to solve exactly this problem.
Here is how you can do it:
class BaseClass { }
interface OnlyBaseClass<TSelf> where TSelf : BaseClass, OnlyBaseClass<TSelf>
{
}
class ChildClass : BaseClass, OnlyBaseClass<ChildClass> { }
class ImpostorClass : OnlyBaseClass<ImposterClass> { }
interface ImposterInterface : OnlyBaseClass<ImposterInterface > { }
Try to compile the above. You will notice that it doesn't compile (due to the two impostors, one a class, one an interface).
The constraint on TSelf can be understood as:
TSelf must: Inherit from BaseClass and implement OnlyBaseClass<TSelf>
...which only a type inheriting from BaseClass and implementing OnlyBaseClass could do.
You could be clever, and do the following:
class AdvancedImpostorClass : OnlyBaseClass<ChildClass> {}
... which will compile. You could prevent these types of impostors from ever getting through into your code by using the same constraints in any methods that accept them as arguments though, like so:
public SomeMethod<TBaseAndInterface>(TBaseAndInterface value)
where TBaseAndInterface: BaseClass, OnlyBaseClass<TBaseAndInterface>
{ }
This is all made possible through the power of F-Bound Polymorphism.
It sounds like you want something like this instead:
abstract class IMyInterface : UserControl { }
Of course IMyInterface is no longer an appropriate name, but any class that derives from IMyInterface would also derive from UserControl, which would satisfy your requirements.
This is not possible. If you can see the interface, you can implement it.
No, there is no way of restricting the implementation of an interface to specific types. Why would you need to? Why does the consumer of an abstraction care about the concrete types that implement that contract? What is your use case?
The case you describe seems to fit an "abstract method in your parent class" (here userControl) , unless the interface already exists for other purposes.
Without default body, derivated classes will have to provide a behavior.

C# Interfaces- only implement an interface in other interfaces

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.

Categories

Resources