Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using var for type declaration instead of explicitly setting interface type

I'm not sure if I'm overthinking this but in the past, I've done something like this when declaring a class:

IMyService myService = new MyService();

Jumping into myService will take you to the IMyService interface.

However, doing the following will (obviously) take you to MyService.

var myService = new MyService();

Which is considered the 'correct' usage, or is this another example of "What's your favourite ice cream flavor?"?

I've looked at the most relevant question but it doesn't really answer my scenario.

like image 971
Dan Atkinson Avatar asked Apr 28 '26 06:04

Dan Atkinson


2 Answers

There is also this option ...

var myService = new MyService() as IMyService;

This will make var myVar = IMyService type ... you can then in other code do something like ...

if(myVar is MyService)
{
    //instance specific stuff 
}
like image 107
iDevForFun Avatar answered Apr 30 '26 19:04

iDevForFun


Well, it depends. Do all the public members of your MyService class come (exclusively) from the implementation of the IMyService interface? Or there are some extra public members (perhaps from the implementation of another interface)? If so, the second "flavor" will allow you seeing these extra members, while the first one will not.

On the other hand, if you are using interfaces, I would say that the "correct" usage is obtaining the type instances from a dependency injection engine or from some kind of factory class or method, but I guess that's outside the scope of this question.

like image 40
Konamiman Avatar answered Apr 30 '26 20:04

Konamiman



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!