var
declares a variable that takes the type from the initial value assigned to it, and was added to support Linq enquires, which can return complex anonymous types. When you write
var data = GetData("");
...
private DataTable GetData(string query)
You are effectively writing
DataTable data = GetData("");
...
private DataTable GetData(string query)
So when you write
string data = GetData("");
...
private DataTable GetData(string query)
You are specifically telling the compiler to assign a
DataTable
value to a
string
variable, and it (rightly) complains.
The problem is that using var saves some people from having to think about what they are doing: all they have to do is write
var myVariable = ...
and the compiler sorts it out without them having any real idea what object type
myVariable
actually is. This leads to confusion like yours and can make code a lot harder to understand and maintain.
Please, use
var
for it's intended purpose - Linq - and not for "normal" variables. It takes almost no extra time to type, and it makes your code a lot clearer.