Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance vs. interface in C# [duplicate]

Possible Duplicates:
Interface vs Base class
When should I choose inheritance over an interface when designing C# class libraries?

So I'm writing my first real program in C#. The program will scrape data from four different websites. My plan is to have one parent class that will look like this:

class Scraper {     string scrapeDate(url);     string scrapeTime(url);     //&c. } 

Then I will have four classes that inherit from it.

The other option is to make Scraper an interface and have four classes implementing it.

What are the differences between these approaches?

like image 676
Hui Avatar asked May 31 '11 14:05

Hui


People also ask

What is the difference between inheritance and interface?

Inheritance is the mechanism in java by which one class is allowed to inherit the features of another class. Interface is the blueprint of the class. It specifies what a class must do and not how.

What is the difference between interface and inheritance in C#?

Interfaces allows to define the structure of common behaviors. Inheritance is useful if you can extract a common implementation of one or more specific behaviors.

Should I use an interface or inheritance?

If whatever you choose don't matter, always choose Interface. It allows more flexibility. It might protect you from future changes (if you need to change something in the base class, the inherited classes might be affected). It also allow to encapsulate the details better.

Can interfaces be inherited?

Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.


1 Answers

Class inheritance represents an "is-a" relationship, e.g., a Tank is a Vehicle. If your situation doesn't at least meet this, choose interface over inheritance.

If the proposed base class doesn't provide default implementations for your methods, this would be another reason to choose interface over inheritance.

In C#, you can only inherit from one class but multiple interfaces. This would be yet another reason to choose interface over inheritance.

Get the idea?

like image 76
Matt Davis Avatar answered Sep 21 '22 21:09

Matt Davis