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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Suraj SahooRank #382 · 6.6K reputationPosted Feb 24, 2015, 6:49 AM EST
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
Pankaj Kumar ChoudharyRank #80 · 24.4K reputationPosted Feb 24, 2015, 7:12 AM EST
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" };
VulpesRank #55 · 29.2K reputationPosted Feb 24, 2015, 7:37 AM EST
http://www.c-sharpcorner.com/UploadFile/b942f9/when-should-you-use-the-var-keyword-in-C-Sharp/
Pradeep ShetRank #595 · 4K reputationPosted Feb 24, 2015, 12:33 PM EST
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.
Jignesh TrivediRank #16 · 50.3K reputationPosted Feb 24, 2015, 6:01 PM EST
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.