开发者

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 int开发者_StackOverflowo 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.


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 
}


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.


What type do you want myService to be? Do you want it to be an IMyService reference or a MyService reference? Once you make that decision, the rest follows.

In other words, only you can answer the question.


It depends on what you mean by correct usage. In the example with an interface you are creating an object of MyService class and storing it into the "pointer" of IMyService class. So your object ius actually an instance of MyService, but your myService var treats it as IMyService interface. So you will not be able to call any methods/access any properties of MyService that are not in IMyService.

With var sample, you are just telling the complier to compute the type of the myService variable from the right side of the declaration. So, in this case it's absolutely identical to MyService myService, that means that you can access all public methods and properties of MyService class via myService variable.


I suppose the real question is why you define myService as an interface. It doesn't have much use unless you want to be able to assign other IMyService's to it. In that case you have to define it as an interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜