I am trying to make the optional parameter of a C# Method to be converted to DBNull
(if it is null
) to be added with Parameter.AddWithValue method.
I saw many solutions (Set a database value to null with a SqlCommand + parameters), extension methods, etc, but i wanted a single line solution.
command.Parameters.AddWithValue("@Municipio", municipio ?? DBNull.Value)
don't work (Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull')
The method: public static void Foo(string bar, string municipio = null)
Unfortunately i can't do string municipio = DBNull.Value
because "default parameter must be a compile-time constant" (what i don't exactly understand the meaning).
I was able to make it work as such:
object obj = municipio == null ? command.Parameters.AddWithValue("@Municipio", DBNull.Value) : command.Parameters.AddWithValue("@Municipio", municipio);
I am very uncomfortable with this, seems like a JavaScript way of doing, i want something like:
if municipio == null ? command.Parameters.AddWithValue("@Municipio", DBNull.Value) : command.Parameters.AddWithValue("@Municipio", municipio);
But somehow i am not being able to make it work like this, perhaps im missing some syntax (i tried many parenthesis/etc combinations).
So my question is, is it good practice the one-line solution i reached, or should i replace it?
Updated to handle if the variable is not initialized. Here is an example:
try: