0

How would I check if da and dtCounts is null before assigning it to a new object?

        var da = new MySqlDataAdapter(cmd);
        var dtCounts = new DataTable();
        da.Fill(dtCounts);
methuselah
  • 12,766
  • 47
  • 165
  • 315

2 Answers2

2

You can't use var in this scenario. Here's a simple example...

MySqlDataAdapter da;
DataTable dtCounts;

// Other code here...

if (da == null)
    da = new MySqlDataAdapter(cmd);

if (dtCounts == null)
    dtCounts = new DataTable();

da.Fill(dtCounts);
Steve Wortham
  • 21,740
  • 5
  • 68
  • 90
0

Another way to do that is using the C# Null-coalescing Operator ?? It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand. So your code can look like:

MySqlDataAdapter da;
DataTable dtCounts;

// Other code here...

da = da ?? new MySqlDataAdapter(cmd);
dtCounts = dtCounts ?? new DateTable();

da.Fill(dtCounts);
afonte
  • 938
  • 9
  • 17