C# Programming – Why Are Objects Instantiated This Way?

cprogramming practicesprogramming-languages

Some times I see an object instantiated this way.

ICustomer oCustomer = new Customer

Obvious but the Customer class is implementing ICustomer interface in this example. Are there any advantages of instantiating an object that way? From my understanding, if a class in implementing an interface it is already following the contract. What is the name of that practice and is there a disadvantage of instantiating an object "normal"(what I usually do) way? I know there are already some existing questions out there, but they don't really highlight the advantages and disadvatages

Interface instantiation vs class instantiation

Customer oCustomer = new Customer

Best Answer

There is one, very important distinction that I think that you're overlooking.

The code you provided is for three things: the declaration of a variable, the instantiation of an object, and initializing that variable with that object.

There is no interface implementation here. Customer needs to implement ICustomer (or do one or two other tricks) for that to compile successfully, but there's no actual implementation going on here.

Now that the terminology is out of the way, let's focus on the meat of the problem: is one better?

This sort of thing falls into the realm of program to an interface. When you declare your variable, you need to give it a type. That type should define the sort of things the variable can do. It is a contract you make with future programmers (or yourself) that oCustomer can only do these sorts of things. You should decide this contract regardless of the source you use to initialize the variable.

If this variable only needs the interface, then using the interface as its type is clearly defining what it can (and can't) do. If this variable really needs to be a full Customer, then double check that you really need that. If you do, then go ahead and make it a Customer. This provides clear communication to future programmers (or you) that the variable needs to be of that type. And if the variable is just some placeholder for your initializer; if its type doesn't really matter, then use var.

The benefits of programming to an interface are described in depth in the link above, but they boil down to allowing you to be flexible. Software inevitably changes. By coding to an interface, you allow this code to remain blissfully unaware when Customer changes - or if you need tomorrow to initialize oCustomer with a VipCustomer instead.

This sort of thing applies in many places throughout programming, not just variable declarations.