Iterating through an object array; foreach(var... vs. foreach(object - c#

object[] objArray = new object[]{"blah", 4, "whatever"};
foreach(var value in objArray) vs. foreach(object value in objArray)
I'm curious as to what the difference is between those, other than var must remain its type after assigned. Is one better than the other? Thanks.

From a purely functional perspective, var is just a shortcut for object here, since objArray's elements are of declared type object.
Using object is a sign to whoever's reading the code that the items in the array are not known to be any type more specific than object. The use of var does not connote this. In the minimal case you posted, it really doesn't make any difference to the clarity of the program which one you use.
If, on the other hand, it is not immediately clear from the context what type of object you are working with, then it may be advantageous to explicitly declare the type. On the other hand, if the type of the elements of the collection you're iterating over is verbose and obtrusive, then it may be advantageous to use var, so that the reader's eyes will be drawn to the logic of the code rather than a mess of generic parameters.

The only difference between var and any other type is that you let the compiler determine the type.

there is no difference between those two, var would be object in this case.

In your example no. But,
When declaring objects you get:
Boxing and Unboxing
However. When using var, it is compiled exactly as if you specified the exact type name.
So var tempval = 5; is the same as int tempval = 5;

Related

How var type decide data type at run time when Iterating ArrayList in C#

I have C# ArrayList and added two items int and string type
Now in for loop Item returns and captured in var type at run time.
How this var type decide data type at compile time????
ArrayList al = new ArrayList();
al.Add(10);
al.Add("A");
for(int i=0; i<2;i++)
{
var val = al[i];
Console.WriteLine("type of value is {0} and {1}",val.GetType(),val);
}
var is used for type inference at compile time. The compiler determines the variable type given all the information it has about the expression al[i] at that time.
Since the indexer property of ArrayList is of type object, the compiler infers the type of val to be object.
At runtime, when calling val.GetType() you have access to the actual type of val: either int or string in your case. But the type of the val variable is still object.
The same mechanism happens if you write:
object o = new int();
Console.WriteLine(o.GetType());
You'd see "System.Int32" although the type of o is object.
Link to fiddle
var is purely compiler "magic", nothing special happens at runtime.
It's your way of saying "compiler, you figure out the correct data type for this variable declaration. I either don't want to, am not too concerned about the specific type, or it's got an unpronounceable name1"
So, the compiler first works out the data type of the expression that's being used to initialize the variable, and gives the variable that type.
Here, the expression's simple - you're accessing the Item property of ArrayList via C#'s indexer syntax. That property returns object, so that's the type of the val variable.
All of that happens at compile time.
1When LINQ was introduced, anonymous types arrived in the language. These are real types generated by the compiler, but they're deliberately given names that, whilst valid names so far as the CLR is concerned, aren't valid names so far as C# is concerned. You don't know their names and even if you did, you wouldn't write them in C#.
It's why var had to be added to the language, the other reasons are convenient outcomes of that decision.
As other said here ArrayList implementation is based on object. Var only infers the type of the right side of the assignment, which in this case is a type of an object, feel free to use in this case object. You should not get any exception. Because ArrayList has not a generic implementation you need to unbox the items to a specific type if you want to treat them differently.
Basically you have a similar effect using a generic list of object.
Here is the implementation of the class, so you can see by yourself the internal implementation
https://referencesource.microsoft.com/#mscorlib/system/collections/arraylist.cs
Hope this helps

What is the advantage of this type inference?

Using type inference we can write:
var myList = new List<int>();
but it's not really helping is it? Because the still requires us to only add ints, so wouldnt it have been easier to just declare the variable of 'int' instead of 'var' ?
The var doesn't change the output of the compiler - it only makes the code shorter.
The only time that var offers anything else is in regards to anonymous types:
var foo = new { Bar = 123 };
It is important to understand that var doesn't mean dynamic or variable (in the sense that it allows the type of the object to vary) - it just allows you to declare a variable and have the compiler infer the type as if you had declared it.
IEnumerable<MadeUpEmbarrassinglyLongClassName> stupidVariable = new IEnumerable<MadeUpEmbarrassinglyLongClassName>();
vs
var stupidVariable = new IEnumerable<MadeUpEmbarrassinglyLongClassName>();
Which is easier to read?
Its more concise than:
List<int> myList = new List<int>();
I guess this might be easier to read that using var though, although in this trivial case there's not much in it.
In addition, if the variable is named sensibly, then the what type it is should be fairly clear anyway.
The var is of unknown type until it is assigned a value. As soon as you assign a value, it becomes the typeof to which it is assigned. This var is used in situation when you can't infer at compile time as to what value will be passed to it. The other situation where var comes in handy is in LINQ queries. Rather than creating a special class to handle your query returns, you simple assign the result to var and it does the rest. You will surely compliment var once you start using LINQ
In your example, there is no advantage. In fact, I believe that code readability suffers a bit (opinion).
The answer to this quesiton boils down to personal preference. The compiler will infer List<int>() if var is used. Which would you prefer to look at? Which would your peers prefer to look at?

In C#, how do inferred variables using var behave with respect to memory and lifecycle?

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.

Why can't I use a "Type" to create a new variable in C#?

int number = 5;
Type dynamicType = number.GetType(); // dynamic type is "int"
dynamicType x = (number as dynamicType);
How would you expect the compiler to treat the variable x later in the code? It wouldn't know anything about it... so it couldn't resolve any method calls etc.
Basically what you're after is dynamic typing which is supported in C# 4 with the "dynamic" pseudo-type:
int number = 5;
dynamic d = number;
// Calls to d are resolved at execution time, so this compiles:
d.ThisWillThrowAtExecutionTime();
Type is an object that represents information about a type. It's not a designator for a variable saying it is of that type.
SomeObject myObject = new SomeObject();
Type t = myObject.GetType();
SomeObject myOtherObject = (SomeObject)Activator.CreateInstance(t);
The ability to do this goes all the way back to .Net v1.0. No need for fancy dynamic typing or anything like that.
Constructing objects with more complex constructors takes a bit more work, but it's the same idea.
You can, just not directly. You can use reflection. Basically you get the fully qualified name of the type (from the Type object) and then call CreateInstance method from an assembly object that contains that type. It should be quite simple to get the assembly reference of the current instance...
I think the Assembly.GetExecutingAssembly() method will do it.
I've written a little about this quite some time ago in a post at: http://frater.wordpress.com/2007/06/24/instantiating-classes-through-reflection-using-c-dynamic-object-creation/
That might help you out some more, though the focus was also on compiling of c# code from within a c# program, to allow for the use of C# as a scripting language, so some of the details might not be completely relevant.
Hope that helps!
Because it wouldn't make any sense.
What would you do next?
The purpose of a cast is to assign the casted object to a variable of the type that you casted it to. In this case, you wouldn't be able to do that, since a field must have a static type at compile time.
What are you trying to do?
dynamicType is an object of type "Type" that holds the Type meta-data information of type "int" hence dynamicType is and instance or object and not a qualified type so you cannot perform instantiation on that.
So, AFAIK you can't use the Type to instantiate 'basic' data types such as int.
You could use it to create objects though:
Object x=Activator.CreateInstance(dynamicType)
The issue is, if you want to call methods or access fields on a dynamic type, you have to use reflection. See the Type class documentation for instructions.

var keyword in C# 3.0 [duplicate]

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.

Categories

Resources