0

I'm actually working on some DB connection and I'm so using a SqlDataReader.

I already created some snippets to help me write faster when it comes to handling DBNULL values.

I was wondering if it is possible to create a snippet for C# that can add lines depending on something like a parameter?

What I'm actually thinking is something like :

string example1 = "";
string example2 = "";
string example3 = "";

try
{
    SqlDataReader reader = command.ExecuteReader();

    while(reader.Read())
    {
        if(reader["example1"] != DBNULL.Value)
        {
            example1 = reader["example1"].ToString();
        }
        else
        {
            example1 = "";
        }

        if(reader["example2"] != DBNULL.Value)
        {
            example2 = reader["example2"].ToString();
        }
        else
        {
            example2 = "";
        }

        if(reader["example3"] != DBNULL.Value)
        {
            example3 = reader["example3"].ToString();
        }
        else
        {
            example3 = "";
        }
    }
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    conn.Close();
}

Is there a way to get it using a snippet typing something like "reader3" where 3 determine the number of fields? (else than just create a bunch of snippet for each possible case)

I tried to search for such a thing, but I didn't find anything, so I guess it might not be possible, but still want to ask, would save a lot of time.

Zoma
  • 321
  • 7
  • 20
  • 1
    Not sure about the snippets, but in this case wouldn't it be better to create a loop over the column names? – Metheny Apr 26 '19 at 06:57
  • @Metheny It might be, but it also depends highly on situations, if there are different types in the reader a loop will be less useful. My colleagues and me are also more used to this format, so I guess it'll stay like that, even if a loop is a good alternative. – Zoma Apr 26 '19 at 07:01
  • 1
    It seems what you want is similar to the built-in switch-case generation snippet, but you need your own custom function. The problem is it seems it's not supported: https://stackoverflow.com/questions/2266415/visual-studio-is-it-possible-to-define-custom-functions-for-use-in-ones-own-co – Metheny Apr 26 '19 at 07:08

0 Answers0