Can we define IDisposable as an abstract class instead of Interface like below. What are disadvantages?
public abstract class absDisposable
{
public abstract void Dispose();
}
public class childClass : absDisposable
{
SqlConnection objConnect = new SqlConnection("connstring");
public override void Dispose()
{
if (this.objConnect != null)
{
this.objConnect.Dispose();
this.objConnect = null;
}
}
}
I wrote that code in the same Interface works, else there is no reason of abstract class with no implementation. This is same way we define Interface, without any implementations.right? However, the question is not the IDisposable only, its about all Interfaces we use. Why don't we simply write the methods we require, why do we go one level more for Implementing Interfaces? Since Interface serves no purpose. We always have to give our own implementations in derived classes, so no question of code re-usability also. And how Interfaces resolve lack of multiple inheritance in c#, if we cannot re-use codes? All I want to know is what situation an Interface proves its presence?
Since C# does not support multiple inheritance, your idea would make it impossible to combine disposability with an existing base class.
Since IDisposable doesn't include any implementation, there is no reason to make it an abstract class.
Related
I recently encountered a question on abstract class.
Functionality of Abstract classes can be achieved by using combination of (Regular class with Protected Constructor + an interface).
What is the benefit of using Abstract Class over (Regular class with protected constructor + interface).
IMHO, Purpose of Abstract class to have common feature that needs to be available across the class hierarchy. It can pose restriction on sub-classes to implement certain features by Abstract methods. It can allow Sub-Classes to override the common behavior.
Abstract Class doesn't serve a purpose of as concrete object. So, It doesn't allow to instantiate the abstract class.
However,We can achieve same thing using Regular Class + interface.
Mark Regular Class constructor as protected, So object can't be created alone
provide default implementation of common features and mark them virtual in case if they need to be overridden by sub class.
Use interface to force sub-classes to implement certain features.
So, Is there any extra feature which Abstract class offer?
I could not think of any other. Interviewers was trying to know what other benefits Abstract class have over Regular Class with protected constructor + interface.
A lot of good reasons. Let's start with an unambiguous one:
public abstract class Smell
{
public abstract string GetAdjective();
public string GetDescription()
{
return "I smell " + GetAdjective();
}
}
public class NastySmell : Smell
{
public override string GetAdjective() { return "really nasty"; }
}
Pretty simple. The abstract class has a function, GetDescription - which relies on the presence of an abstract method GetAdjective.
How could you do this with ProtectedConstructor+Interface? You can't have Smell implement the interface (for lots of reasons, but a big one being that any derived classes would also inherit the implementation and wouldn't be required to implement anything new) - but that means that it's function can't refer to the method:
public interface SmellInterface
{
string GetAdjective();
}
public class Smell
{
protected Smell() { }
public string GetDescription()
{
// how do I call GetAdjective here? I have no reference to it!
}
}
But here's another, even more compelling reason:
public abstract class SomeFancyClass
{
protected string name;
protected string server;
protected abstract string implementer { get; }
public string Generate()
{
if (name == "something")
HandleGlobally(name);
else
HandleSpecifically(name);
}
public void HandleGlobally(string server)
{
// code
}
public abstract void HandleSpecifically(string server);
}
... if you make this class a combo ProtectedConstructorClass + Interface, you split up code into two separate spots - and suddenly, you have to look through two halves to get the full picture of what's going on!
public interface AbstractHalf
{
// data property of 'implementer'
// method of 'HandleSpecifically()
}
public class NonabstractHalf
{
// data fields of 'name' and 'server'
// methods of 'Generate()' and 'HandleGlobally'
}
... why would you want to do this? Your class is a distinct, logical entity. Why would you split it up into two separate parts: the non-abstract versus the abstract? It'd just make it harder to read and troubleshoot. And it'd get worse, the more code and abstract declarations were made in the class.
The main benefit of the abstract class is to force the developer to create a subclass that inherits from the abstract class in order to use base/shared functionality and fields.
You cannot directly new-up an abstract class. You can new-up a regular class + interface, and you are not forced to inherit or override anything in the base.
With an abstract class, you can reduce the number of files - i.e. no interfaces, but most folks would probably like to keep those for registration with an IoC container and dependency injection.
One thing that I can think of is that by using an abstract class you can force a specific implementation simply by not marking a method or property as virtual, while using an interface you can't prevent classes from implementing the interface but not derive from your base class.
Another benefit of using an abstract class is that you can simply add functionality to your abstract class without having to worry about having all your derived classes implementations - again, since you can't prevent a class from implementing an interface without deriving from your base class.
Also, an abstract class can have protected fields, methods, events etc', but an interface can't.
It all boils down to the fact that you can't force classes that implement your interface to derive from your "regular" base class.
First of all, there is many questions and answers about differences between Abstract Class and Interfaces like: this. There are a lot of remarkable answers. But most of them are about programming and syntax.
I want to look from Design Perspective:
I think that Abstract Class can not play the Role of Interface (+ Regular Class)
in Software Design.
Abstract Class:
The main goal of Abstract Class is Abstraction Principle. To overcome this complexity, Abstract classes are used to make Hierarchies in similar looking classes. All classes in the hierarchy are extending base classes functionalities and extending types of base classes.
Interface:
However, Interfaces are used for Interactions between classes. These classes can be similar or not. They can be from different hierarchies and different types.
Also, they are huge difference between inheriting from a class (even Abstract class) and implementing an interface. Interfaces are not TYPES. They are shared boundary across which two or more separate components of a computer system exchange information.
I have and interface defining a bunch of different properties and a State property that is a compact summary of all the other.
So I have a common interface named IStateful
interface IStateFul
{
string State { get; set; }
}
I have some classes implementing this interface in different ways - one asks for user input, another read the values from a service, one could get data from a DB.
But all of them have to compute the state in exactly the same way to be "compatible" with each other. So the implementation of State in the different classes have to use the other property in exactly the same way to compute the state string.
As of today I copy and paste the state implementing method from a class to the other. This is obviously the worst option.
Other options could be
Common abstract base class (I tried this and it's ankward, the abstract class have to implement abstractly all the interface method that it does not care at all, then the derived classes have to override them all)
Another class with a static method to be called (a "serializer" ???)
An extension method for the interface (just the same as option 2 but with different sintactic sugar)
There is a common pattern to follow? Or is there a basic design flaw that I'm missing to see?
In an abstract class you should only mark the methods that need to be overridden as abstract, otherwise mark them virtual:
public abstract class MyBase
{
protected virtual void DoSomething()
{
//My Implementation here
Console.WriteLine("Base implementation");
}
//Will give compile-time error if you don't override this in derived class
protected abstract void DoSomethingElse();
}
Then in your derived classes you can use either the base implementation of the virtual methods or override them and the abstract methods will need to be implemented:
public class Derived : MyBase
{
protected override void DoSomethingElse()
{
Console.WriteLine("Derived implementation");
}
}
public static void Main(String[] args)
{
var derived = new Derived();
derived.DoSomething(); //Base Implementation
derived.DoSomethingElse(); //Derived implementation
}
If using an interface is not absolutely required by your design, you can use an abstract class instead of the interface and not both at the same time. It will work practically the same way but allows you to define a method/property implementation.
Your case is a common pattern addressed by abstract classes.
I would define the interface IRequireState
public interface IRequireState
{
bool GetState();
}
And use that for all classes requiring state. There is a programming principle called "The Interface Segregation Principle" (ISP) which basically states that you should ONLY implement an interface in the classes where it makes sense to do so.
According to the Open Closed Principle you can always subtitute a derivative, so for example, if you have 3 classes, all implementing the IRequireState you can then type code like:
foreach(var job in myListOfJobs)
if(job.GetType() == typeof(IRequireState))
((IRequireState)job).GetState();
I hope that helps you on the path to good Object Oriented design. Make sure to read up on the SOLID principles. They help alot in these questions.
If you have some jobs that do the same GetState() thing, then it would make sense to have a base class which implements the same interface, but you're then free to ALSO have jobs with various, different GetState() implementations.
This question already has answers here:
Why do both the abstract class and interface exist in C#?
(11 answers)
Closed 9 years ago.
One interviewer has asked me the below question and I couldn't answer:
Why do we need Interfaces when abstract classes exist?
Whatever the methods we are writing in interface those we can write in Abstract class also. Then why do we need interfaces separately?
Can anybody please tell what is the reason?
Advance thanks...
There are several differences,
Abstract classes can have only one parent class, whereas a class can implement several interfaces.
Interfaces cannot contain any implementation, abstract classes can (they can have abstract methods in addition to not abstract methods).
Interfaces are great to focus on a 'view' we can have on a class. This view can be shared by multiple classes implementing the interface.
For instance, DataTable implements IListSource and ISerializable. So, depending on the context, you can view it as a list source to read its data or as a class which instances can be serialized. When you do so, you focus on a specifc view you can have of an instance.
Interface represents a contract, while you can have several implementations of that contract in different (abstract) classes.
public interface IExample
{
void Do();
}
public abstract class DoFirst : IExample
{
public void Do()
{
Console.WriteLine("Doing it the first way");
}
}
public abstract class DoSecond : IExample
{
public void Do()
{
Console.WriteLine("Doing it the second way");
}
}
public class DoFirstConcrete : DoFirst, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with first.");
}
}
public class DoSecondConcrete : DoSecond, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with second.");
}
}
You abstract class is a partial implementation. Interfaces are contracts, to know what your abstract class can do. You need an interface to describe it.
You can implement multiple interfaces, but only inherit from one abstract class.
An interface is an empty shell, there are only the signatures (name / params / return type) of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern
Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It's more about a guy saying "these classes should look like that, and they got that in common, so fill in the blanks!".
Quoted e-satis from here (much more information too):
What is the difference between an interface and abstract class?
You can't inherit from multiple abstract classes, but you can implement multiple interfaces.
I have just seen on the comment to a blog post:
Base abstract generic class is a bad
choice in most situations
Is this true, if not why?
What insight(s) leads to this statement?
I agree, because anything that inherits an abstract generic class will not be polymorphic with the base class. That is, if you have
abstract class myBase<T>
then you create
class myThing: myBase<thing>
class myOtherThing: myBase<otherThing>
you can't create methods that work against myThing and myOtherThing since they do not share an ancestor. There's no point in the base class being abstract, really, it might as well just be a class.
But if you have a base class
abstract class myBase
class myBase<T>: myBase
as is a common pattern for generic classes (like IEnumerable - using interfaces), then they all share myBase.
(edit) I just read the actual blog post - and actually, the comment is not really valid in that situation. The "abstract generic base class" he's referring to, Range<T> inherits IEnumerable<T> which inherits non-generic interface IEnumerable. So it's not really an "abstract generic base class." But generally I think it's true.
"Most situations" is outrightly vague. A generic abstract class (or interface) is a bad idea if the only common ancestor between descendants of such class is System.Object (as noted by other commenters of this question).
Otherwise (as in, if you do have a meaningful common ancestor), it's a good idea if you want to "rename" or "specialize" members. Consider this example:
// Meaningful common ancestor for the working classes.
interface IWorker
{
object DoWork();
}
// Generic abstract base class for working classes implementations.
abstract WorkerImpl<TResult> : IWorker
{
public abstract TResult DoWork();
object IWorker.DoWork()
{
return DoWork(); // calls TResult DoWork();
}
}
// Concrete working class, specialized to deal with decimals.
class ComputationWorker : WorkerImpl<decimal>
{
override decimal DoWork()
{
decimal res;
// Do lengthy stuff...
return res;
}
}
In this example, DoWork() was redefined in the abstract class, becoming concrete and specialized in ComputationWorker.
One problem with abstract generic base class is that you can't type decorate :
public abstract class Activity<TEntity>
{
public Activity() { }
protected virtual object Implementation { ... }
}
public abstract class CompensableActivity<TEntity,TCompensation> : Activity<TEntity>
where TCompensation : Activity<T>, new()
{
public CompensableActivity() { }
protected override object Implementation
{
get { new Wrapper(base.Implementation, Compensation); }
}
private Activity<TEntity> Compensation
{
get
{
var compensation = new TCompensation();
if(compensation is CompensableActivity<TEntity,Activity<TEntity>)
{
// Activity<TEntity> "does not meet new() constraint" !
var compensable = comp as CompensableActivity<TEntity, Activity<TEntity>>;
var implement = compensable.Implementation as Wrapper;
return implement.NormalActivity;
}
else { return compensation; }
}
}
}
Kragen makes a good point. Anything that is less than 50% of your code is "the wrong choice in the majority of situations".
However, even though nowhere near 50% of your classes should be generic abstract base classes, it also isn't less of a good thing than any other language feature.
For example, BindingList<T> could be considered an abstract generic base class. It's a generic container, and sorting requires you to derive from it and override ApplySortCore.
KeyedCollection<TKey, TItem> doesn't just act like an abstract generic base class, it is one. To use it you MUST derive from it and implement GetKeyForItem.
I disagree with the crowd here. In some cases an abstract generic class is the best design.
A good example in .NET can be found in System.Collections.ObjectModel where the KeyedCollection allows you to override and implement a typed serializable dictionary collection easily!
I elided most of the code but this is the principle:
public class NameCollection : System.Collections.ObjectModel.KeyedCollection<string, INamedObj>
{
protected override string GetKeyForItem(INamedObj item)
{
return item.Name;
}
}
Well, statistically speaking if someone asked me "should I make this class an abstract generic class?", the answer would almost certainly be no - in 3 years of .Net development I think I can count the number of abstract classes that I've written that had generic type parameters on one hand.
Other than that I can't see any particular reason for an abstract generic class to be considered a Bad Thing - its just not that common.
There are situations where an abstract base class is useful thing.
We have several .net applications that use different database engines. Several sql server, a couple of mysql and a bunch of oracle apps.
We have a generic common database object which is based on an abstract class that is a factory that returns the proper database object in a factory setting based on the type of database.
That way if I am starting a new application, all I have to do is load this database object, pass in the type, pass in the connection string, and bam... i'm set...
I guess what I'm trying to say is it all depends on the context and how its actually used.
I have a interface as follows
public interface IX
{
void MethodA();
void MethodB();
}
I have two method contracts in the interface MethodA and MethodB. I will define set of classes that will implement the above interface. Out of these two methods MethodA is common for all the types that will implement the interface. I can define a abstract class as follows
public abstract class XBase:IX
{
public void MethodA()
{
// Common behaviour implementation
}
public abstract void MethodB();
}
And inherit this class to all the types that need to implement the above interface. It works.
But here in the abstract class i add 'public abstract void MethodB();'. It looks like repetition of the MethodB contract.
Why C# does not permit partial interface implementation if the class is abstract?. The above interface has only two methods. suppose one interface has 10 methods and 5 are common functionality and 5 are not, we are forced to add the 5 methods that are not common in the abstract class?
Because the C# language specification says so. Chapter 13.4.7:
Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class.
Why the C# designers chose to specify the language like this is probably best answered by Eric Lippert. I'd personally guess at reducing the odds that unintended method hiding occurs, producing error messages that are very hard to interpret. I would personally have been more comfortable requiring the use of the overrides keyword for the interface method implementation. But they chose not to.
The reason it doesn't support this is because your superclass doesn't fulfil the contract. The only way for an abstract class to force implementation on its subclasses is to define abstract methods.
If you don't want the abstract class to have those abstract methods defined then you have to tell the subclasses to implement the interface instead.
Question would have to be, why would it be a problem having 5 abstract methods on your superclass?
Interfaces do pass along the contract requirement to each other, so as far as you have IFoo and IBar : IFoo, then classes inheriting from IBar must implement both interfaces, as clearly IBar cannot implement the members of IFoo itself. Why this behavior could not be extended to abstract base classes, I don't know. I'm sure there is a good reason, and since Hans posted the spec, it's obviously intentional.
As a please do not try this at home approach, you could do something like
class Derived : Base, IFoo
{
public void MethodB()
{
}
}
abstract class Base
{
public Base()
{
if (!(this is IFoo))
throw new InvalidOperationException("must implement IFoo");
}
public void MethodA() { }
}
interface IFoo
{
void MethodA();
void MethodB();
}
Which has the abstract base implement the methods it wants and then force the derived classes to implement the rest by enforcing that the derived classes implement the interface. The derived classes would then be responsible for implementing the methods that are not already in the base class. The problem with this approach is that this is a runtime requirement, not compile time.
How would you handle a situation where you have
interface IFoo {
void MethodA();
void MethodB();
}
abstract class Base: IFoo {
public void MethodA() {}
// MethodB gets implicitly generated
}
class Derived: Base {
public void MethodB() {}
}
Could you then do this:
Base myBase = ...
myBase.MethodB();
Ok you could, since MethodB is implicit. But what if you would later decide to remove the interface IFoo from the Base class? You just broke the Base's contract..Solution would be that generated methods would be explicit interface implementations, but that brings another kind of pain.
You can switch from 'abstract' to 'virtual' in the method declaration and provide an assertion:
public abstract void MethodB();
becomes
public virtual void MethodB()
{
Contract.Require( your condition );
}
I don't think abstract class or interface is doing any injustice in your scenario rather as per SOLID principles (specifically: Interface Segregation Principle) : https://msdn.microsoft.com/en-us/library/dn178470(v=pandp.30).aspx
It says large interfaces should be split into smaller and more specific ones so that client classes are not forced to implement methods they do not use at all. Utilizing this principle would solve your problem.