views:

89

answers:

2

Possible Duplicates:
Abstract classes vs Interfaces
Interface vs Base class

Hi,

In C# when should we use interfaces and when should we use abstract classes? Please explain with example

A: 

use interfaces when you don't when your describing a contract and abstract classes when your implmenting functionality that will be shared among deriving classes.

To examples of usage could be template pattern and Strategy pattern

Rune FS
Technically i can understand the difference, and when I use an abstract class I am reusing the base class code in my derived classes. But why I need to write an interface and implement it. Anyway I am going to define the methods only in the class that implements it. So if two classes implement the interface that I write and defines the method in the interfaces, I will be able to use the classes and methods even If I dont write an interface correct? So what advantage will I achieve when I use interfaces?
SARAVAN
A: 

Abstract class, if you want to implement basic functionality and some properties/methods that must be overwritten by the implementer:

public abstract class Entity
{
     public int Id { get; set;}

     public bool IsNew { get { return Id == 0; } }

     public abstract DoSomething(int id); // must be implemented by concrete class
}

Interface, if you want to define, which properties/methods a class must contain, without implementing any functionality:

public interface IRepository
{
    object Get(int id);
    IEnumerable<object> GetAll();
}
Dave
Hm ... would you ever do both? See the accepted answer to http://stackoverflow.com/questions/2705163/c-abstract-classes-need-to-implement-interfaces.
Hamish Grubijan