'C# - Single class to manage generic classes

I have a base class Database and 2 classes deriving from this class, MSSQLDatabase and SQLCEDatabase.

I can use Database.SetDatabase(new MSSQLDatabase()) then I am able to fetch the instance by using Database.GetDatabase<T>(), and as an example use Database.GetDatabase<T>().Connect().

However I would like to know if there is a way I can specify the desired class for ex. MSSQLDatabase once, then just call Database.Connect() and have the Database class cast to the specified class?



Solution 1:[1]

From my point of view, you will have to think differently. Database should be a single class that would take in the constructor a parameter like an interface IDb and the MSSQLDatabase and SQLCEDatabase should implement the IDb. Now you can call the new Database(new MSSQLDatabase()) once and from here you can call Database.Connect() every time knowing that behind your code will work with MSSQLDatabase. With this approach you would use "Aggregation" instead of yours that is more like a "Composition".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1