Search code examples
c#if-statementstored-proceduresswitch-statementisnullorempty

How to Switch-Case many variables in C# (that checks if the values are null or empty) to replace if-else-if chain


How to Switch-Case many variables in C# (that checks if the values are null or empty) to replace the giant if-else-if chain (+20 else-ifs) . How can I have less and more efficient code replacing my code with Switch statements :

        con.Open();
        SqlCommand cmd = new SqlCommand("usp_AddPublisher", con);
        cmd.CommandText = "usp_AddPublisher";
        cmd.CommandType = CommandType.StoredProcedure;
        if (String.IsNullOrEmpty(data.Account_Num))
        {
            cmd.Parameters.AddWithValue("@AccountNum", "");
        }
        else
            cmd.Parameters.AddWithValue("@AccountNum", data.Account_Num);
        if (String.IsNullOrEmpty(data.publisher))
        {
            cmd.Parameters.AddWithValue("@publisher", "");
        }
        else
            cmd.Parameters.AddWithValue("@publisher", data.publisher);
        if (String.IsNullOrEmpty(data.addr1))
        {
            cmd.Parameters.AddWithValue("@addr1", "");
        }
        else
            cmd.Parameters.AddWithValue("@addr1", data.addr1);

I tried but it's too long :

  con.Open();
        SqlCommand cmd = new SqlCommand("usp_AddPublisher", con);
        cmd.CommandText = "usp_AddPublisher";
        cmd.CommandType = CommandType.StoredProcedure;
switch (String.IsNullOrEmpty(data.Account_Num))
        {
            case true:
                cmd.Parameters.AddWithValue("@AccountNum", "");
                break;
            case false:
                cmd.Parameters.AddWithValue("@AccountNum", data.Account_Num);
                break;

        }
  switch (String.IsNullOrEmpty(data.publisher))
            {
                case true:
                    cmd.Parameters.AddWithValue("@publisher", "");
                    break;
                case false:
                    cmd.Parameters.AddWithValue("@publisher", data.publisher);
                    break;
            }
            switch (String.IsNullOrEmpty(data.addr1))
            {
                case true:
                    cmd.Parameters.AddWithValue("@addr1", "");
                    break;
                case false:
                    cmd.Parameters.AddWithValue("@addr1", data.addr1);
                    break;
            }

Solution

  • Given all you're doing is using "" as the value when a string is null or empty, you're just coalescing null to "". So just do that:

    cmd.Parameters.AddWithValue("@AccountNum", data.Account_Num ?? "")
    

    If you've not come across the null coalescing operator ?? before, you can read about it in the documentation.