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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With