c#.net
Q)what is difference between var keyword and data types? when we go for var and data types?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Feb 24, 2015, 11:01 PM
Hi,
Var introduced in c#3.0, this is way of defining variable implicitly typed and the compiler determines the type at the compile type. there is only difference between datatype and var is using var we are defining variable type implicitly and data type explicitly
var i = 50; // implicitly typed
int i = 50; //explicitly typed
The var keyword is very useful when:
1.We have a long class name so that our code is not so readable. var makes it short and sweet.
2.We use LINQ and anonymous types that help us reduce the code (reduce effort to create a new class).
hope this will help you.
Pradeep ShetPosted Feb 24, 2015, 5:33 PM
var is a variant datatype that means its datatype is decided once you assign the value to compile type.
datatype are predefined which hold specific type of value.
Similar way there is dynamic which decides the variable datatype at runtime.
VulpesPosted Feb 24, 2015, 12:37 PM
http://www.c-sharpcorner.com/UploadFile/b942f9/when-should-you-use-the-var-keyword-in-C-Sharp/
Pankaj Kumar ChoudharyPosted Feb 24, 2015, 12:12 PM
We we are using var keyword for a explicit data type such as (string,int etc) then there is no difference .
Exa : var as=12;
int ab=12; Both gives the result asme.
Now question rises when we should use a var keyword.
1. If you have simple value or predefine data type then you should use Data types(int ,string).
2. We you have a complex data then you should use var like(LINQ)
3. If you have a undefine type then you should use Var
Exa:
var obj = new { s = "asdf" };
Suraj SahooPosted Feb 24, 2015, 11:49 AM
There has been a lot of dispute over the use of var. My general rules are the following.
Basically, the goal is to make it easier to read the code. If you feel that var suffices because the assignment is obvious, use var. Use the full type name as a hint for the reader when you feel it's necessary.
CC:--http://programmers.stackexchange.com/questions/42863/explicitly-defining-variable-data-types-vs-using-the-keyword-var
Hope this helps.
Accept if helps anyway.
Thanks