I hope the extension methods ThrowArgumentNullExceptionIfNullOrEmpty
and ThrowNullReferenceExceptionIfNullOrEmpty
are straightforward.
I have a property in my class called ConnectionString
. I can set this property through a method called SetConnectionString
.
public static void SetConnectionString(string connectionString)
{
_connectionString = connectionString.ThrowArgumentNullExceptionIfNullOrEmpty("connectionString", Localizer.GetString("0x000000004"));
}
My reason why I don't have
public static string ConnectionString { get; set; }
but
public static string ConnectionString { get { return _connectionString; } }
is because I want the property to be read-only and throw an ArgumentNullException
if the argument in SetConnectionString
is null or empty.
Since the class
is static
, it's possible for ConnectionString
to be null
(or an empty string if I do this: return _connectionString ?? ""
).
Part 1
In the code below I check the arguments for null or an empty string but to prevent an exception occurring when calling OpenConnection
(see Part 2 for more on this method) I also check if the _connectionString
(private
variable of the ConnectionString
property) is not null or empty (empty is for the internal connection string of the OleDbConnection
object). Here I decided the exception should be a NullReferenceException
because it's not directly an argument of the method.
Is this the correct approach to handle this situation? Consider that the code in between the checks might and might not have an impact on the application if the using
fails.
public static int GetHighestID(string table, string column)
{
_connectionString.ThrowNullReferenceExceptionIfNullOrEmpty(Localizer.GetString("0x000000000"));
table.ThrowArgumentNullExceptionIfNullOrEmpty("table", Localizer.GetString("0x000000001"));
column.ThrowArgumentNullExceptionIfNullOrEmpty("column", Localizer.GetString("0x000000002"));
// Some other things are happening here ...
using (var connection = new OleDbConnection(_connectionString))
using (var command = new OleDbCommand(string.Format("SELECT MAX({0}) FROM {1}", column, table), connection))
{
OpenConnection(connection);
return (int)command.ExecuteScalar();
}
}
Part 2
The OpenConnection
method as mentioned before is included below.
public static void OpenConnection(OleDbConnection connection)
{
connection.ThrowArgumentNullExceptionIfNull("connection", Localizer.GetString("0x00000000C"));
connection.ConnectionString.ThrowArgumentNullExceptionIfNullOrEmpty("connection.ConnectionString", Localizer.GetString("0x00000000F"));
if (connection.State != ConnectionState.Open)
connection.Open();
}
I also here check if the OleDbConnection
object is not null and that the internal connection string is not null or an empty string. My intention is to always use this method when opening the connection with the database.
Again, is this the correct approach to handle this situation?