Why implicit upcast on declaration?

Viewed 73

Why would I want to implicitly upcast at declaration? My question arises from the following code from my text book.

private readonly IList<Inventory> _cars = new ObservableCollection<Inventory>();

Why wouldn't I just do this instead.

private readonly ObservableCollection<Inventory> _cars = new ObservableCollection<Inventory>();

If I'm just saving space, why not just do this instead?

private readonly var _cars = new ObservableCollection<Inventory>();

Thanks,

2 Answers

This is not about savings keystrokes; it is about the principle of "least privilege".

This:

private readonly var _cars = new ObservableCollection<Inventory>();

And this:

private readonly ObservableCollection<Inventory> _cars = new ObservableCollection<Inventory>();

Explicitly make the statement that _cars is observable. The code that you write afterwards may end up depending on that, even if it was not your original design. In general you want to use the barest interface that does the job, so if there is a some part of your code that does not need to know that something is observable, it is a good practice to statically type your variables so that they use a non-observable interface.

When you write:

private readonly IList<Inventory> _cars = new ObservableCollection<Inventory>();

You make it clear that you don't want to write code dependent on _cars being observable, and the compiler will error and scream at you if you do, which is good.

In addition to the last privilege principle, there's 2 more reasons to do this:

  1. Using OOP through a base class. Examples include storing triangles and circles into a list of shapes (classic college example), and factories (which can return any number of concrete implementations through a reference).

  2. Getting access to .Net boxing fake interfaces. For example, IConvertible convertible = 5; -- int doesn't have interfaces, in fact no value type does, but when boxed (cast to object) the framework allows you to access them as though they did implement a bunch of interfaces.

Related