Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the practical use of using interface reference variable in C#?

Tags:

c#

interface

I know interface reference variable can refer to any object that implements its interface. But what is the practical use of using a reference variable? We can achieve the same by using an object, then why use a reference variable?

like image 545
Amanshu Kataria Avatar asked Mar 24 '26 21:03

Amanshu Kataria


1 Answers

The question leaves lots of room for interpretation, but here's mine:

Every object variable is actually a reference variable in C#:

MyClass c = new MyClass();
IMyInterface i = new MyClassThatImplementsInterface();
object o = new object();

All the above are reference variables as they "point" to reference types. I suppose that by your question you mean: Why should I write

IMyInterface i = new MyClassThatImplementsInterface();

instead of

MyClassThatImplementsInterface i = new MyClassThatImplementsInterface();

or even

object i = new MyClassThatImplementsInterface();

Simple answer is: You can call all the methods and properties defined by IMyInterface in the first and second case, and you can not in the last case.

But why not use the second case? Well, this is mostly why people use interfaces at all. Sometimes you don't know the implementing class. Or it is defined internally in some library. All you need to know, however, is that when you call a method you get some object in return that conforms to the interface you know. So that's all you need (and sometimes that's also all you get).

For example:
I've recently created an application that can display modules defined in plugin DLLs, which are dynamically loaded by a launcher application. The launcher application adds buttons for each plugin and changes the UI when a plugin button is pressed.

The launcher application knows nothing about the plugins - apart from one interface that contains properties returning titles, icons, a UserControl for the UI, etc.

I don't have any classes I can work with. All there is is a factory class that returns an instance of an object that implements my interface. And that's all you need to have.

like image 166
Thorsten Dittmar Avatar answered Mar 26 '26 13:03

Thorsten Dittmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!