1

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

Community
  • 1
  • 1
SARAVAN
  • 14,571
  • 16
  • 49
  • 70
  • 3
    @BlaXpirit: Would a question about whether to declare variables at the start of a method or at the place of first use prove that Java is a bad clone of C++? Your comment is pointlessly provocative, with no evidence of either your main point or your snipe at C# being "bad". – Jon Skeet Aug 21 '10 at 20:49
  • @Bla Hi, I got answer from your recommended questions. Technically i can understand the difference, and when I use an abstract class I am re-using 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 hte interface. So if two classes implement the interface that I write and defines the method in the interface, I will be able to use the classes and methods even If I don't write an interface correct? So what advantage will I achieve when I use interfaces? – SARAVAN Aug 21 '10 at 21:10
  • My head started to hurt while I was reading the previous comment. So I'll give you a helpful link that contains lots of other links that make your head hurt: http://duckduckgo.com/?q=interface+vs+abstract+class – Oleh Prypin Aug 22 '10 at 22:42

2 Answers2

4

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();
}
davehauser
  • 5,844
  • 4
  • 30
  • 45
0

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
  • 21,497
  • 7
  • 62
  • 96
  • 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 Aug 21 '10 at 21:08