Initializing an Object

  • Thread starter Thread starter Emmanuel Mathew
  • Start date Start date
E

Emmanuel Mathew

Hi friends,

I have a method which is given below

public IDbConnection SetConnection(string connectionString)

{

try

{

IDbConnection connection;

switch (dbType)

{

case (int)DatabaseType.odbc:

connection = new OdbcConnection(connectionString);

break;

case (int)DatabaseType.oledb:

connection = new OleDbConnection(connectionString);

break;

case (int)DatabaseType.sqlClient:

connection = new SqlConnection(connectionString);

break;

default:

break;

}

return connection;

}

catch (Exception ex)

{

throw ex;

}

}

When this is compiled, a warning comes like "the object Connection is
unassigned or never used. So how can I initilize this object?

Thanks in Advance
Emmanuel Mathew
 
Emmanuel,
Do you really need the "connection" variable?

You can initialize it here:
IDbConnection connection = null;


I however would probably simply return it, and avoid the variable.
case DatabaseType.odbc:

return new OdbcConnection(connectionString);

break;


Rather then silently fail, I would throw an exception if I did not have a
valid DatabaseType.

throw new ArgumentOutOfRangeException("dbType", dbType, "Invalid
Database type")


It appears that your Try/Catch is not doing anything, I would not bother
coding it.
catch (Exception ex)
{
throw ex;
}

http://msdn.microsoft.com/msdnmag/issues/04/06/NET/default.aspx

If you did need the Try/Catch, I would consider using "throw" over "throw
ex", as "throw" will preserve the stack trace.
catch (Exception ex)
{
throw;
}

Hope this helps
Jay
 
Back
Top