0

Let say I have one method, now what is the difference in when I pass an interface as a parameter and a passing a class as a parameter?

Ex1.

public void GetPrice(IPartsData partsData)
{
     Do something
}

Ex2.
public void GetPrice(PartsData partsData)
{
     Do something.
}

Here in Ex1 I am pssing an interface and in Ex2 I am passing class in GetPrice method.

ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58
Rinkesh
  • 1
  • 3

4 Answers4

1

In both cases you are passing through the instance of the class. However, when you use the interface in the parameter, you are limited to the functionality described in the interface unless you cast it.

It also means that the method is a little more friendly as other implementations can use the method as well and is also more unit testable.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
1

Ex. 1 is better practice since using interfaces promotes a loosely coupled design.

This means it is easier to scale, maintain and unit test. (Interfaces are much easier to mock when it comes to unit testing.)

See this stack overflow post for the difference between loose and tight coupling.

Cool Breeze
  • 1,289
  • 11
  • 34
0

Its depends on your attitude on behavior of your method, If you want to allow the user (Other developer whom using your method) have his own implementation of your IPartsData you should accept interface as parameter, In this case callers can call your method with difference implementation of class PartsData. But If you want use exactly specified implementation of IPartsData which you have implemented before you should accept just class of PartsData as parameter. This is some sort of IoC concept in OOP programming.

Mohammad Nikravesh
  • 947
  • 1
  • 8
  • 27
0

One specific use case comes to mind in connection with a scenario where you have 2 classes but both classes have a different BaseClass. This means you can't write your method with a parameter of type BaseClass. Instead you would define an interface that fits both classes and assign it to both classes. This enables you to pass both classes to the method having a parameter of type BaseClass.

ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58