I realise that the title may be very confusing, so to explain what I would like to do, I will illustrate how I can easily solve the same problem in PHP.
E.g. I give the user of my application a choice database types (i.e. MySQL, MSSQL, etc).
In my code I would like to have only one function for each operation rather than a function for each database as I explain below.
NOT
main.php
<?php
function mysql_get_users() {
//Foo
}
function mssql_get_users() {
//Foo
}
if($dbtype == "mysql") {
echo mysql_get_users();
}
if($dbtype == "mssql") {
echo mssql_get_users();
}
?>
BUT
main.php
<?php
if($dbtype == "mysql") {
include("mysql.php");
}
if($dbtype == "mssql") {
include("mssql.php");
}
echo get_users();
?>
mysql.php
<?php
function get_users() {
//Foo
}
?>
mssql.php
<?php
function get_users() {
//Foo
}
?>
Now I have the same problem, but in C# using Visual Studio 2010. Since I cannot do this:
if(dbtype=="mysql") {
public static MySqlConnection connect(String connectionString)
{
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
return connection;
}
}
The big problem with the above is particularly that I cannot put an if-clause around a method(function), then I have to face the problems of the types which are unique to each database type amongst the fact that I have to include the returned connection variable in each method related to database function.
So, any thoughts on how to fix this and make it work like the PHP example above? I am neither an expert nor a newbie on C#, but I learn quite quickly.
Personally, I think you need to approach the problem differently. This is where object-oriented programming is your friend. Basically, you would abstract out the database-specific stuff so the calling code knows nothing about which database it is using. If you were doing it from scratch, here is a very over-simplified example:
So then, in your client code, you choose which type of database to instantiate, and then call the same functions regardless of what kind it is: