In my project I have defined an interface to describe the methods that each of my different database connection classes must have. This is called IDatabaseConnectivityObject. Each of my classes implements this interface to make sure that they all contain the same methods for running queries, making connections etc etc.
Consider the following code:
IDatabaseConnectivityObject adoDataBaseConnection = new DbProviderFactoryConnection();
DbProviderFactoryConnection adoDataBaseConnection = new DbProviderFactoryConnection();
Will the above lines both behave the same? If so why? If not then why not? What are the benefits of both?
It may be a really stupid question but I havent used interfaces all that long and I am not sure what line 1 does. It was my understanding that you couldnt make an instance of an interface as it merely defines behaviour so how is that line possible?
At runtime yes. The difference is that if you declare the variable of type
IDatabaseConnectivityObjectthen at compile time you will be able to see only the members of this interface on the variable. If on the other hand you declare it asDbProviderFactoryConnectionthen you will see all the members of this class.As a good practice it is recommended to always work with the highest possible type in the hierarchy when declaring the variable (
IDatabaseConnectivityObjectin this case) which allows you to access all members that the consumer will need.