Let’s say we have a code portion like this:
IProduct product = ProductCreator.CreateProduct(); //Factory method we have here
SellThisProduct(product);
//...
private void SellThisProduct(IProduct product)
{
//.. Do something here
}
//...
internal class Soda : IProduct
{}
internal class Book : IProduct
{}
How can I infer which product is actually passed into SellThisProduct() method in the method?
I think if I say GetType() or something it will probably return the IProduct type.
GetTypegets you the exact runtime type of an object. From the documentation:You can also use
isto determine if an object is an instance of a specific type:Why do you need the exact runtime type, though? The entire point of an interface is that you should be hiding the implementation details behind the common interface. If you need to take an action based on the type, that’s a big hint that you’re violating the encapsulation it provides.
One alternative is to use polymorphism:
Since these three types aren’t related at all, inheritance from a common type doesn’t make sense. But to represent that they share the same capability of making noise, we can use the IVocalizer interface, and then ask each one to make a noise. This is a much cleaner approach: now you don’t need to care what type the object is when you want to ask it to make a noise: