This question already has answers here:
What advantages does using var have over the explicit type in C#? [duplicate]
(9 answers)
Closed 9 years ago.
i have some confusing about var and not var initialization.
var x=10;
x=12;
what is the difference between those initialization in C# ?
i knew var is keyword is used for following kind of ways.
When the type is complex to write, such as a LINQ query (the reason for var in the first place) use var.
Thanks,
Siva
This one compiles.
var x=10;
This one does not assuming you are trying to initialize x in this scenario.
x=12;
It has to be:
int x = 12;
Now what is the difference between var x=12; and int x = 12; nothing. They are both resolved at compile time.
The first one is used to declare and assign a local variable x. The new variable declared will automatically get the (strong and non-dynamic) type of the right-hand side of the =. That is type int in your example.
The second one is used to assign (only) to a variable or property that has been declared already elsewhere.
To use var keyword, there must be an expression which possesses a type on the right hand side of the equals (=) for it to compile.
var myNumber = 1; will work, as var will be compiled to int as a type. myNumber = 1 will not work, since myNumber is not declared. If you want to declare a variable with nothing on the right side of the equals sign, then you must specify the type explicitly, i.e int myNumber.
Personally, I would only use var when it's obvious what it will compile to... e.g.
var myNumber = 1;
var name = "some name";
var lst = List<int>();
less obvious...
var data = GetData();
Sure, you can go to the method to see what the return is, but it can be more difficult to read for other developers.
var x = 10;
is equavalent to
int x = 10;
var is excellent syntactic sugar.
When you write x = 10, your x must be declared before.
var
It was introduced in C# 3.0
1 ) var declarations are resolved at compile-time.
2) Errors are caught at compile time.
When you dont know what type are you dealing with it is better to go with var it gets it type from the right hand side of the assignment where it is defined.
var x =10;
x=12;
In the first case the compiler resolved the declaration at run time
Lets assume if you would have done
var x=10;
x="I am String";
will throw error since the compiler has already decided that the type of x is System.Int32 when the value 10 was assigned to it. Now assigning a string value to it violates the type safety
Advantages
var comes in handy when you combine it with the c# 3 anonymous types and generics anonymous types are still clr types but you can't have the type name at coding time
However it is better to use naming conventions for better readability
The var aliases any type in C# and its type will be determined by C# compiler or it is implicitly typed.
But in
x = 12;
you have to explicity determine the type and for example write :
int x= 12;
Using var has no performance consideration and you can use it freely.
Related
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Using var outside of a method
class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?
In function/method, i can declare a var type variable,then why can't, i do it in class ?
Thanks.
// method variable
var X;
is never valid - even inside a method; you need immediate initialization to infer the type:
// method variable
var X = "abc"; // now a string
As for why this isn't available for fields with a field-initializer: simply, the spec says so. Now why the spec says so is another debate... I could check the annotated spec, but my suspicion would be simply that they are more necessary for method variables, where the logic is more complex (re LINQ etc). Also, they are often used with anonymous types (that being the necessity for their existence); but anonymous types can't be exposed on a public api... so you could have the very confusing:
private var foo = new { x = 123, y = "abc"}; // valid
public var bar = new { x = 123, y = "abc"}; // invalid
So all in all I'm happy with the current logic.
If you really don't know the type of object your instance variable will hold, use object, not var. var doesn't mean "i don't know", it means "infer the type for me" - this is why it can never be used on class members.
Because C# doesn't support this level of type inferencing. Your alternatives are to use a language, such as F#, that does support this level of type inferencing or beg the C# team to implement the feature. I've got a pretty good guess which one you'll have more luck with...
var in C# is a implicitly typed local variable used to infer the type from the RHS of the given expression, which needs to be resolved at compile time. When you declare a var with no RHS value in the class definition, there is no way for the compiler to know the type that you are trying to assign to var.
C# doesn't support implicit typing for class variables.
Because the actual type of a var is inferred from the context in which it is used. For fields (class member variables), there is no such context.
You can argue that the intent is quite obvious if you would write var _users = new List<User>() as a field declaration.
The problem is that not all field declarations contains an assignment which is required to infer the type. (You might want to initialize a field through the constructor)
Mixing both var and normal type declarations would look like a nasty soup. Therefore it's not possible.
(at least that's my guess)
Yes, the var keyword is only allowed for local variables.
It was introduced in the language to be able to handle an anonymous type, that only exists in a local scope. As the anonymous type is limited to the local scope, it makes sense to only allow the var keyword in a local scope.
Additionally, it never works to use the var keyword without specifying a value, as that is used to infer the data type:
var x = "asdf"; // works
var x; // doesn't work
The normal way of declaring a variable is using a specific data type. Use the var keyword when you can't specify a data type (e.g. when the type is anonymjous) or when the type is superflous (e.g. repeated literally in the value). Example:
var x = new { Key = 42, Name = "asdf" };
var y = new System.Text.StringBuilder();
It is all because of the Build order. You can declare var in only methods. Compiler builds everything but methods first and thats why the type of the object will be clear to the compiler if you use it inside of a method. Jon had a great answer about this but can't seem to find.
Ok, I've been reading everything I can find on var, and I'm pretty sure I've got a handle on their basic behaviors and type inference. I've always been a big proponent of explicit types, so var makes me a little edgy when I'm reading code. So I have a couple of questions regarding its memory usage and the behavior of a variable declared with var over the course of that variable's lifecycle in memory.
Since var is an inference to an explicit or anonymous type, will its memory be allocated in the same place its corresponding type would be or is var universally created on the heap and accessed as if it were an object. As an example:
int i = 5; // puts this on the stack
var i = 5; // does this also go on the stack?
Does a declared var have a constant type once it is initialized or can it be adjusted as well? I ask this because I can't find in the documentation that specifies this, and I just read something in this SO question by #Eric Lippert:
a variable is a storage location whose
contents change
Having tested the following code, I see an implicit conversion exception even at the IDE level. I don't have the experience with LINQ at this point to run a similar test with respect to anonymous types. Do they follow this same behavior? Will the IDE recognize a type mismatch at design time or would such code receive a run-time exception?
var i = 5; // Initializes as int, value is 5
i = "Steve"; // Type casting error
Finally, is there ever a situation that you can think of where you may know a type at design time but it would be prudent to use var anyway? I ask because I've seen code samples where people do this, and from what I've read it strikes me as just lazy-coding.
EDIT: I realize there are a lot of articles talking about this topic, but I haven't found any that answer these questions specifically (though some hint one way or another). I would be happy to read any document you feel is relevant to these topics, just please post a link.
var is 100% syntactic sugar in the C# compiler. When the actual IL is generated, the type is explicitly defined. var-declared variables do not behave any differently from their explicitly-defined counterparts. The dearth of information you're seeing is coming from the fact that var is simpler than you're assuming. There is quite literally no difference between these two lines:
var i = 10;
int j = 10;
(Other than the fact that you see the words var and int, of course; they are functionally completely identical).
var variables are infered by the compiler, they are really just syntactical sugar, there is no difference between:
var i =0;
and
int i = 0;
in the compiled code.
They were added for the purpose of allowing anonymous types, e.g.
var MyVar = new { prop1="A string", prop2=5};
Yes var varables recognise a type mismatch at compile time, the compiler dynamically creates a class for them when it compiles. e.g. the below would not compile:
var MyVar = new { prop1="A string", prop2=5};
MyVar = "Fred";
As others have said, var has no effect on how the variables behave in terms of memory - it just means you don't specify the name. For anonymous types you couldn't specify the name, first because you don't know it at compile time, and second because the names are deliberately "unspeakable" - they're not valid in C#. (Generally they contain <> for example.)
The IL generated for code using var and code using an explicit name is exactly the same. Just as a normal variable can't change type, nor can a variable declared using var... so in your example where you try to assign the value "Steve" to a variable which has an implicit type of int, you'll get a compile-time error exactly as if you'd explicitly declared it to be of type int.
As for when to use var and when not to, I have a few rules of thumb:
Obviously if you want the variable to have a type other than the compile-time type of the assigned expression, you've got to do it explicitly
For constructor calls, it's always clear what the the type is even if you're using var
var is useful for emphasizing what the code is meant to do rather than how
Often I use var if the explicit name would be extremely long - particularly for generics with multiple type arguments.
Basically it's all about readability: if the code is easier to read using var, go for it. If not, don't. Note that this isn't the same as saving typing... code is generally read more than it's written, so think about your reader. Eric Lippert wrote a great note when tech reviewing the first edition of C# in Depth, which is worth a read.
Simple answer: exactly the same as normal variables.
var declarations are translated into specific (strong) types at compile-timee. var is simply a method of automatic type inference, and has nothing to do with dynamic languages. At the end of the day, it's just the compiler being clever and translating var into what actual type you want.
"Since var is an inference to an explicit or anonymous type, will its memory be allocated in the same place its corresponding type would be or is var universally created on the heap and accessed as if it were an object"
The important thing about var, is that the compiler changes the var statement to the actual type at compile time, so:
var number = 1;
Will get changed to:
System.Int32 number = 1;
...by the compiler. And as such the memory locations for storage of these types is no different. var is essentially syntactic sugar. So, method local declarations of value types will get stored on the stack, reference pointers will get stored on the stack with the referenced objects on the heap.
Once you have declared a variable as var, because this is translated into its full type by the compiler, you can't then dynamically change the type:
var i = 5;
i = "Steve";
...is invalid, because its already been declared as an Int32.
Anonymous types follow a similar behaviour, where a type is created by the compiler during compilation.
"Finally, is there ever a situation that you can think of where you may know a type at design time but it would be prudent to use var anyway?"
Personally, I follow a simple pattern:
For primitives, I always put the type:
int i = 5;
string name = "Matt";
For complex types, I mostly do this:
var instance = new MyComplexTypeInstance();
For LINQ results, I stick to var:
var result = from i in something select i;
For methods, if the method is descriptive of the type being returned, then I will use var.
var instance = GetInstance();
Whereas, more complex method names, I'd put the actual type:
Result result = DoSomethingWeirdAndWonderful();
Each developer will find something they are comfortable with, the choice is yours. As var is only really a design-time thing, its all syntactic sugar.
Picking up C#, can't seem to find any useful reference to this, other than examples.
So, what is Dim in C#?
In VB, Dim declares a variable of a particular type (or of variable type, if you don't specify one). If you Dim x as Foo, that declares a variable of type Foo called x.
In C#, the equivalent is to state the type followed by the variable's name, as in:
Foo x;
int i;
You can also assign in the same step:
Foo x = new Foo();
int i = 6;
C# supports type inference, so you can also do:
// Compiler infers type of x and i based on this assignment.
var x = new Foo(); // x is now of type Foo
var i = 10; // i is now of type int
A Dim without a corresponding type in VB is similar to declaring a type as Object in C#:
object o = ...; // An object instance can hold any value or reference type.
Assuming that you mean Dim in VB, C# uses either var or the name of the type to declare a new type
string myString = "Hello";
// is the same as
var myString = "Hello"; // type is inferred
Note that the var keyword is not a variant type, like in VB. It is an implicitly typed variable.
This is actually a bit tricky, because Dim can be used in several ways. The first case is if you explicitly provide the type of the variable when declaring it. In this case, it corresponds to C# declaration that contains the type name:
// Visual Basic
Dim num as Integer
// C#
int num;
The second case is if you use an initialization expression, but don't specify the type explicitly. In this case, VB (at least recent versions) use type inference to deduce the type. This corresponds to C# var keyword:
// Visual Basic
Dim str = "Hello world"
// C#
var str = "Hello world"
Finally, there is a third case - you can declare Visual Basic variable without giving any type and without providing the initialization expression (at least with Option Strict turned off). In this case, VB.NET declares the variable as a value of type Object, but also allows you to invoke any methods of the object. This is quite close to what C# 4.0 does with the new dynamic keyword:
// Visual Basic
Dim sth
sth = new Random()
sth.Next()
// C#
dynamic sth;
sth = new Random();
sth.Next();
[EDIT]
Finally, the last case of use Dim in Visual Basic is to declare arrays. In C#, arrays are treated as just another data type, so the declaration is similar to what I wrote earlier for integers/strings:
// Visual Basic
Dim ints(10, 10) as Integer
// C# - we need to initialize the array if size is specified
int[,] ints = new int[10, 10];
// C# - we can use type inference too
var ints = new int[10, 10];
[/EDIT]
(I'm not really a VB expert, but I think these are the three possible cases. Please correct me if I'm wrong!)
The similar equivalent would be like
object Obj;
or any other datatype such as
int myInt;
string myString;
var could also be used as implicitly typed. Others would be explicitly typed. var was introduced for LINQ queries though.
Dim is a keyword used for declaration of variables used in VB.NET. I don't know about any usage in C#. I would say its (rough) equivalent would be the var keyword, provided that we are talking about VB 9 and C# 3. But I think it's useless to go into fights about details before we know what is the intended question anyway ;)
I can suggest Learning C# 3.0 (and later, maybe C# 3.0 in a Nutshell and C# in Depth) to learn C#. It's probably a good idea to learn the language fundamentals and start "thinking in C#", instead of trying to "translate" or "convert" your thoughts from VB to C# (or any other language, for that matter).
Edit: That said; you do want to compare the new language you're learning to the one(s) you already know whilst you go along, to learn the differences between the languages. In my opinion, when learning a new language, it's more about grasping the principles and fundamental differences :)
This question already has answers here:
Closed 13 years ago.
Duplicate:
What to use var or object name type
I couldn't understand the need of var keyword in C# 3.0 What is the advantage in using it.
i saw this question but did not understand the real purpose of using it
It's mostly present for LINQ, when you may use an anonymous type as the projection:
var query = from person in employees
where person.Salary > 10000m
select new { FullName=person.Name, person.Department };
Here the type of query can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.)
It's also practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines:
List<Func<string, int>> functions = new List<Func<string, int>>();
var functions = new List<Function<string, int>>();
but the second one expresses it in a more compact way.
Of course this can be abused, e.g.
var nonObviousType = 999999999;
but when it's obvious what the type's variable is, I believe it can significantly increase readability.
The primary reason for its existence is the introduction of anonymous types in C#. You can construct types on the fly that don't have a name. How would you specify their name? The answer: You can't. You just tell the compiler to infer them for you:
var user = users.Where(u=> u.Name == "Mehrdad")
.Select(u => new { u.Name, u.Password });
It's a shorthand way of declaring a var. Although "int i = new int()" isn't too much to type, when you start getting to longer types, you end up with a lot of lines that look like:
SomeReallyLong.TypeName.WithNameSpaces.AndEverything myVar = new SomeReallyLong.TypeName.WithNameSpaces.AndEverything();
It eventually occurred to someone that the compiler already knew what type you were declaring thanks to the information you were using to initialize the var, so it wouldn't be too much to ask to just have the compiler do the right thing here.
Here are a couple of advantages
Less typing with no loss of functionality
Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
Makes it so you don't have to write the same name twice in a variable declaration.
Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
Shameless self promotion. I wrote a blog entry on this subject awhile back that dived into when I thought the use of var was appropriate and contains relative information to this topic.
http://beta.blogs.msdn.com/jaredpar/archive/2008/09/09/when-to-use-type-inference.aspx
Linq expressions don't return a predefined type, so you need a 'generic' variable declaration keyword to capture that and other places where anonymous types are used.
Used carefully, it can make refactoring easier by decoupling a method's return type from the variable that captures it.
Having to put the same name on the same line twice for the same statement is really kind of silly. It's a pain to type something like this:
.
ReallyLongTypeName<SomeOtherLongTypeName> MyVariable = new ReallyLongTypeName<SomeOtherLongTypeName>();
In short:
minimize the need for typing the variable type twice
essential in supporting anonymous types, e.g. as returned by LINQ queries
The real need for the var keyword was to support anonymous types in C# 3.0--which in turn were required to properly support LiNQ (Language Integrated Querying).
Without using var you could never do something like this:
var person = new { Name = "Peter", Age=4};
Which means that you couldn't execute execute the following linq query because you wouldn't know how to assign it to a variable:
[var/sometype] dogsFixedQuery = from myDog in kennel select new {dogName = myDog.FirstName + " " + myDog.OwnerLastName, myDog.IsNeutered, dogLocation = kennel.Address};
The utility of anonymous types will be more apparent if you start to create more complex linq queries with multiple levels of returns and joins.
The fact that you can use var in other ways to avoid typing out something like IEnumerable<Dictionary<List<string>,IOrderedCollection<DateTime>> myBadDesign = getBadDesignController().BadDesignResults("shoppingCart");
is just a side-effect/bonus in case you're a lazy typer =)
There are cons for readability if you start calling vars in disparate locations but if you're using var for a strong type and the compiler can determine the type of your variable than any reader should be able to determine it as well.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What’s the point of the var keyword?
Hello everyone,
I want to confirm whether my understanding is correct. If I do not use LINQ, then the only benefit of using var is to make brevity? Is that correct understanding?
No, you can use var to construct anonymous types, regardless of whether or not you're using LINQ:
var anon = new { Name = "Anonymous", Age = 42 };
It's also easier for working with types like this. When you have very long generic types, the type name can get in the way of visually identifying the variable name as part of a declaration.
Dictionary<string, Dictionary<int, ICollection<object>>>
especially if you go back through and change it to
Dictionary<string, IDictionary<int, ICollection<object>>>
From msdn:
Beginning in Visual C# 3.0, variables
that are declared at method scope can
have an implicit type var. 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:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
MSDN Link Here
If you're not using LINQ, var allows you to only declare the type of the variable once, instead of twice.
Example
var myObject = new MyObject();
vs
MyObject myObject = new MyObject();
This can only be done locally, and is also useful for declaring anonymous types.
Example
var myAnon = new { Name = "Something", Count = 45 };
Other than for LINQ queries I would be very cautious in using the var keyword. There are specific instance when you just need an anonymous type but this is few and far between I think. Var can lead to very confusing code as you have no idea what the type you are dealing with when reading the code unless you use the intellisense crutch.
It worries me more and more that I see so many snippets and bits of code that do the following... it's lazy and not what the var keyword was intended for:
// Not too bad but still shouldn't be done because the only gain you have is keystrokes
var Something = new SomeObject();
// Type here is not obvious, are you getting an int, double, custom object back???
var Something = GetLengthOfSpaghettiCode();
So use it for LINQ... use it for anonymous types (if you do use anonymous types outside of LINQ you should really scrutinize why you need to).
Quote from MSDN (very last line of article) regarding use of var:
However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.
Don't use it as a short cut to save keystrokes, the next guy looking at your code will appreciate it.
Pretty much, yes. var may be used wherever the compiler can infer the type of the variable from whatever value you are assigning to it. (The type inference rules are quite complex however, so you may want to read the C# specification for a full understandin.)
It's not quite correct in that the var keyword is required for defining anonymous types. For example:
var foo = new { abc = 1, def = 2 };
which can be used outside of LINQ queries as well as inside, of course.
I don't think using var should be a problem - and I prefer it for exactly the reasons of code readability. First of all, var is only syntactic sugar and just gets compiled away to a proper type when IL is emitted. And as far as the code readability goes, it makes more sense to focus on the purpose the variable is used for, and how it is assigned than just its type. VS .NET editor shows the type in the line following it anyway - if you just hover on it. So this shouldn't be a problem at all. And as far as the debugging goes - if you see Autos/Local/Watch windows - they display the types of all the members.
It makes more sense for me to see code like this:
var customers = GetCustomerList();
foreach (var customer in customers)
{
customer.ProcessOrders();
}
as opposed to
List<CustomerObjectDeserializedFromWebService> customers = GetCustomers();
foreach (CustomerObjectDeserializedFromWebService customer in customers)
{
customer.ProcessOrders();
}
var is in its fairness limited to using in local variable declarations which are also initialized at the time of declaration. And in that one case, if you omit the actual type it definitely improves readability IMO.
EDIT: And it would unfair on my part not to warn against the usages as below:
var x = 20;
This is not good; when the literal is applicable to multiple types, you need to know the default type of the literal and hence understand what is infered for the type of x. Yes, by all means, I would avoid such declarations.
I believe it is also used in the WCF (Windows communication Foundation) when dealing with data obtained via webservices and the like.
I've also found that the use of var also eases refactoring in low-coupled designs. This is because we tend to strong type variables, but normally the code that follows is expecting weaker types. Using var you'll offset type changes to the compiler.