1

I'm not sure what this is call or how to google for an explanation but here goes

let said I have a interface call IView and a class inherited IView call View class. In some projects I see the below code:

IView view = new View();

Why do that? Why not just do

var view = new View();

Is there a purpose for declaring a interface then create a View object? why not do the second step?

Jack
  • 9,843
  • 23
  • 78
  • 111

2 Answers2

2

If you use the var keyword, the type of the variable will be automatically detected and will probably be of the type View instead of IView. It's more clear to the reader of your code that you actually meant to have an IView reference.

The idea of interfaces, is that it doesn't matter which class implements them, so your code is built upon the knowledge that this .. thing.. implements all IView's properties and methods, disregarding which class it is.

A setup like this will allow you to easily insert different classes later. You could substitute this line for a call to an IView factory of which you don't know at all which class instance it returns.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
1

You might need view to be something other than whatever View is, for example, if View is a class of SpecialView, then var view won't allow you to later assign something that is a GenericView to it even though they both have an IView interface.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57