Reputation: 1435
What is the difference between variable
and string
in c#
Why the c#
is supporting only this
var data = GetData("");
Why not this?
string data = GetData("");
Or it will support both? Which one is better to use ? How it is implemented?
private DataTable GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
cmd.Connection = cn;
da.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
return dt;
}
}
}
}
Upvotes: 0
Views: 655
Reputation: 148180
The type of var is not specified in code rather compiler infers it from the code
. GetData probably does not return a string
.
An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent, MSDN.
Edit based on updated OP
You can not assign DataTable to string they are two different types. You can use DataTable
instead of var if you want to specify the type yourself and you do not want to the compiler to determine it for you using var
.
string data = GetData("");
Upvotes: 4
Reputation: 48736
var
is not a data type. Declaring something as var
is synonymous to saying "Compiler, I want you to figure out what type this variable should be by looking at the object I assign to it". Assume you had this:
var myString = "This is a string!";
The C# compiler looks ahead to see that you are assigning a string to myString
and it knows that myString
is going to be a string
type. As far as the compiler is concerned, it is exactly the same as:
string myString = "This is a string!";
As far as what you should use, its entirely your preference and choosing one over the other will not impact your code at all. Personally, I use var
because I feel its redundant to declare an object's type twice, like this:
MyClass myClass = new MyClass();
Instead I prefer:
var myClass = new MyClass();
Again, its entirely up to you and your personal coding style. Hope this clears up your questions!
Upvotes: 0
Reputation: 63105
if GetData
method return type is string
below will work
string data = GetData("");
but return type of GetData
method is DataTable
, you can change the code as
DataTable data = GetData("");
Or use var
and compiler will determines the type for you.
Upvotes: 0
Reputation: 10218
Var
is an implicit type.
It aliases any type in the C# programming language.
The aliased type is determined by the C# compiler, where as string is string variable type
Upvotes: 0