As at the link: http://msdn.microsoft.com/en-us/library/bb383973.aspx
...An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type...
But I have such piece of code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null) Response.Redirect("Default.aspx");
StringBuilder sb = new StringBuilder();
foreach (var item in Session)
{
sb.Append("Session Parameter: [");
sb.Append(item);
sb.Append("]<p />Guid Value: [");
sb.Append(Session[item] + "]");
}
Response.Write(sb.ToString());
}
I'm getting such error in Visual Studio:
Argument 1: cannot convert from 'object' to 'string' for the line:
sb.Append(Session[item] + "]");
But item is identifying at runtime as a string type as I looked in the debugger.
When I have read about var at msdn/in books I thought that var doesn't relate to RTTI-stuff. Compilers just changes the variable with this implicitly type on explicitly type like string, int etc at compile time.
Why did I catch such error?
A var declaration in C# is strongly typed but in this case you are dealing with a non-generic collection type in the value Session. This causes C# to choose object for the type of item and hence you get a later error trying to use item in a position that requires a string.
For non-generic collections you need to still explicitly type the iterator variable in a foreach block
foreach(string item in Session) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With