Free mag vol1 | Page 867

CHAPTER 21  ADO.NET PART I: THE CONNECTED LAYER The same holds true for member return values. For example, consider the following simple C# Console Application project (named MyConnectionFactory), which allows you to obtain a specific connection object based on the value of a custom enumeration. For diagnostic purposes, you simply print out the underlying connection object using reflection services, and then enter the following code: using System; ... // Need these to get definitions of common interfaces, // and various connection objects for our test. using System.Data; using System.Data.SqlClient; using System.Data.Odbc; using System.Data.OleDb; namespace MyConnectionFactory { // A list of possible providers. enum DataProvider { SqlServer, OleDb, Odbc, None } class Program { static void Main(string[] args) { Console.WriteLine("**** Very Simple Connection Factory *****\n"); // Get a specific connection. IDbConnection myCn = GetConnection(DataProvider.SqlServer); Console.WriteLine("Your connection is a {0}", myCn.GetType().Name); // Open, use and close connection... Console.ReadLine(); } // This method returns a specific connection object // based on the value of a DataProvider enum. static IDbConnection GetConnection(DataProvider dp) { IDbConnection conn = null; switch (dp) { case DataProvider.SqlServer: conn = new SqlConnection(); break; case DataProvider.OleDb: conn = new OleDbConnection(); break; case DataProvider.Odbc: conn = new OdbcConnection(); break; 813